Changes on the server.json format and the API (#562)
This commit is contained in:
parent
4962609697
commit
b21c6f564d
22 changed files with 4056 additions and 5608 deletions
|
|
@ -26,6 +26,8 @@ func NewNoneHandler(cfg *config.Config) *NoneHandler {
|
|||
}
|
||||
|
||||
// RegisterNoneEndpoint registers the anonymous authentication endpoint
|
||||
// WARNING: This endpoint is intended for local development and automated tests only.
|
||||
// It should NOT be enabled in production environments as it bypasses normal authentication.
|
||||
func RegisterNoneEndpoint(api huma.API, cfg *config.Config) {
|
||||
if !cfg.EnableAnonymousAuth {
|
||||
return
|
||||
|
|
@ -33,13 +35,13 @@ func RegisterNoneEndpoint(api huma.API, cfg *config.Config) {
|
|||
|
||||
handler := NewNoneHandler(cfg)
|
||||
|
||||
// Anonymous token endpoint
|
||||
// Anonymous token endpoint for development/testing only
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-anonymous-token",
|
||||
Method: http.MethodPost,
|
||||
Path: "/v0/auth/none",
|
||||
Summary: "Get anonymous Registry JWT",
|
||||
Description: "Get a short-lived Registry JWT token for publishing to io.modelcontextprotocol.anonymous/* namespace",
|
||||
Summary: "Get anonymous Registry JWT (Development/Testing Only)",
|
||||
Description: "Get a short-lived Registry JWT token for publishing and editing servers in the io.modelcontextprotocol.anonymous/* namespace. This endpoint is intended for local development and automated testing only.",
|
||||
Tags: []string{"auth"},
|
||||
}, func(ctx context.Context, _ *struct{}) (*v0.Response[auth.TokenResponse], error) {
|
||||
response, err := handler.GetAnonymousToken(ctx)
|
||||
|
|
@ -61,6 +63,10 @@ func (h *NoneHandler) GetAnonymousToken(ctx context.Context) (*auth.TokenRespons
|
|||
Action: auth.PermissionActionPublish,
|
||||
ResourcePattern: "io.modelcontextprotocol.anonymous/*",
|
||||
},
|
||||
{
|
||||
Action: auth.PermissionActionEdit,
|
||||
ResourcePattern: "io.modelcontextprotocol.anonymous/*",
|
||||
},
|
||||
}
|
||||
|
||||
// Create JWT claims for anonymous user
|
||||
|
|
|
|||
|
|
@ -43,8 +43,14 @@ func TestNoneHandler_GetAnonymousToken(t *testing.T) {
|
|||
assert.Equal(t, auth.MethodNone, claims.AuthMethod)
|
||||
assert.Equal(t, "anonymous", claims.AuthMethodSubject)
|
||||
|
||||
// Check permissions
|
||||
require.Len(t, claims.Permissions, 1)
|
||||
// Check permissions - should have both publish and edit permissions
|
||||
require.Len(t, claims.Permissions, 2)
|
||||
|
||||
// Check publish permission
|
||||
assert.Equal(t, auth.PermissionActionPublish, claims.Permissions[0].Action)
|
||||
assert.Equal(t, "io.modelcontextprotocol.anonymous/*", claims.Permissions[0].ResourcePattern)
|
||||
|
||||
// Check edit permission
|
||||
assert.Equal(t, auth.PermissionActionEdit, claims.Permissions[1].Action)
|
||||
assert.Equal(t, "io.modelcontextprotocol.anonymous/*", claims.Permissions[1].ResourcePattern)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
|
@ -18,8 +19,9 @@ import (
|
|||
// EditServerInput represents the input for editing a server
|
||||
type EditServerInput struct {
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token with edit permissions" required:"true"`
|
||||
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
Version string `query:"version" doc:"Version to edit (e.g., '1.0.0')" required:"true" example:"1.0.0"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded version to edit" example:"1.0.0"`
|
||||
Status string `query:"status" doc:"New status for the server (active, deprecated, deleted)" required:"false" enum:"active,deprecated,deleted"`
|
||||
Body apiv0.ServerJSON `body:""`
|
||||
}
|
||||
|
||||
|
|
@ -31,14 +33,14 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
huma.Register(api, huma.Operation{
|
||||
OperationID: "edit-server",
|
||||
Method: http.MethodPut,
|
||||
Path: "/v0/servers/{server_id}",
|
||||
Path: "/v0/servers/{serverName}/versions/{version}",
|
||||
Summary: "Edit MCP server",
|
||||
Description: "Update an existing MCP server (admin only). Requires version query parameter to specify which version to edit.",
|
||||
Description: "Update a specific version of an existing MCP server (admin only).",
|
||||
Tags: []string{"admin"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *EditServerInput) (*Response[apiv0.ServerJSON], error) {
|
||||
}, func(ctx context.Context, input *EditServerInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
|
|
@ -53,9 +55,20 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
return nil, huma.Error401Unauthorized("Invalid or expired Registry JWT token", err)
|
||||
}
|
||||
|
||||
// Get current server to check permissions against existing name
|
||||
currentServer, err := registry.GetByServerIDAndVersion(input.ServerID, input.Version)
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// URL-decode the version
|
||||
version, err := url.PathUnescape(input.Version)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid version encoding", err)
|
||||
}
|
||||
|
||||
// Get current server to check permissions against existing name
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
@ -64,27 +77,42 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
}
|
||||
|
||||
// Verify edit permissions for this server using the existing server name
|
||||
if !jwtManager.HasPermission(currentServer.Name, auth.PermissionActionEdit, claims.Permissions) {
|
||||
if !jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionEdit, claims.Permissions) {
|
||||
return nil, huma.Error403Forbidden("You do not have edit permissions for this server")
|
||||
}
|
||||
|
||||
// Prevent renaming servers
|
||||
if currentServer.Name != input.Body.Name {
|
||||
if currentServer.Server.Name != input.Body.Name {
|
||||
return nil, huma.Error400BadRequest("Cannot rename server")
|
||||
}
|
||||
|
||||
// Prevent undeleting servers - once deleted, they stay deleted
|
||||
if currentServer.Status == model.StatusDeleted && input.Body.Status != model.StatusDeleted {
|
||||
return nil, huma.Error400BadRequest("Cannot change status of deleted server. Deleted servers cannot be undeleted.")
|
||||
// Validate that the version in the body matches the URL parameter
|
||||
if input.Body.Version != version {
|
||||
return nil, huma.Error400BadRequest("Version in request body must match URL path parameter")
|
||||
}
|
||||
|
||||
// Edit the server using the version_id from the current server
|
||||
versionID := currentServer.GetVersionID()
|
||||
if versionID == "" {
|
||||
return nil, huma.Error500InternalServerError("Server version ID not found in metadata", nil)
|
||||
// Handle status changes with proper permission validation
|
||||
if input.Status != "" {
|
||||
newStatus := model.Status(input.Status)
|
||||
|
||||
// Prevent undeleting servers - once deleted, they stay deleted
|
||||
if currentServer.Meta.Official != nil &&
|
||||
currentServer.Meta.Official.Status == model.StatusDeleted &&
|
||||
newStatus != model.StatusDeleted {
|
||||
return nil, huma.Error400BadRequest("Cannot change status of deleted server. Deleted servers cannot be undeleted.")
|
||||
}
|
||||
|
||||
// For now, only allow status changes for admins
|
||||
// Future: Implement logic to allow server authors to change active <-> deprecated
|
||||
// but only admins can set to deleted
|
||||
}
|
||||
|
||||
updatedServer, err := registry.EditServer(versionID, input.Body)
|
||||
// Update the server using the service
|
||||
var statusPtr *string
|
||||
if input.Status != "" {
|
||||
statusPtr = &input.Status
|
||||
}
|
||||
updatedServer, err := registry.UpdateServer(ctx, serverName, version, &input.Body, statusPtr)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
@ -92,7 +120,7 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
return nil, huma.Error400BadRequest("Failed to edit server", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *updatedServer,
|
||||
}, nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -2,14 +2,20 @@ package v0_test
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
|
|
@ -21,313 +27,616 @@ import (
|
|||
)
|
||||
|
||||
func TestEditServerEndpoint(t *testing.T) {
|
||||
// Create registry service and insert a common test server
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
||||
// Publish a test server that will be used across test cases
|
||||
testServer := apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original test server",
|
||||
Status: model.StatusActive,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/test-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/test-server",
|
||||
},
|
||||
Version: "1.0.0",
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
published, err := registryService.Publish(testServer)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, published)
|
||||
assert.NotNil(t, published.Meta)
|
||||
assert.NotNil(t, published.Meta.Official)
|
||||
|
||||
testServerID := published.Meta.Official.ServerID
|
||||
// Create registry service and test data
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Publish a second server for permission testing
|
||||
otherServer := apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Other test server",
|
||||
Status: model.StatusActive,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/other/test-server",
|
||||
Source: "github",
|
||||
ID: "other/test-server",
|
||||
// Create test servers for different scenarios
|
||||
testServers := map[string]*apiv0.ServerJSON{
|
||||
"editable": {
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Server that can be edited",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/editable-server",
|
||||
Source: "github",
|
||||
ID: "testuser/editable-server",
|
||||
},
|
||||
},
|
||||
Version: "1.0.0",
|
||||
}
|
||||
otherPublished, err := registryService.Publish(otherServer)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, otherPublished)
|
||||
assert.NotNil(t, otherPublished.Meta)
|
||||
assert.NotNil(t, otherPublished.Meta.Official)
|
||||
|
||||
otherServerID := otherPublished.Meta.Official.ServerID
|
||||
|
||||
// Publish a deleted server for undelete testing
|
||||
deletedServer := apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/deleted-server",
|
||||
Description: "Deleted test server",
|
||||
Status: model.StatusDeleted,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/deleted-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/deleted-server",
|
||||
"other": {
|
||||
Name: "io.github.otheruser/other-server",
|
||||
Description: "Server owned by another user",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/otheruser/other-server",
|
||||
Source: "github",
|
||||
ID: "otheruser/other-server",
|
||||
},
|
||||
},
|
||||
Version: "1.0.0",
|
||||
}
|
||||
deletedPublished, err := registryService.Publish(deletedServer)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, deletedPublished)
|
||||
assert.NotNil(t, deletedPublished.Meta)
|
||||
assert.NotNil(t, deletedPublished.Meta.Official)
|
||||
|
||||
deletedServerID := deletedPublished.Meta.Official.ServerID
|
||||
// Create the test servers
|
||||
for _, server := range testServers {
|
||||
_, err := registryService.CreateServer(context.Background(), server)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Create a deleted server for undelete testing
|
||||
deletedServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Server that was deleted",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/deleted-server",
|
||||
Source: "github",
|
||||
ID: "testuser/deleted-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), deletedServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set the server to deleted status
|
||||
_, err = registryService.UpdateServer(context.Background(), deletedServer.Name, deletedServer.Version, deletedServer, stringPtr(string(model.StatusDeleted)))
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create a server with build metadata for URL encoding test
|
||||
buildMetadataServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/build-metadata-server",
|
||||
Description: "Server with build metadata version",
|
||||
Version: "1.0.0+20130313144700",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/build-metadata-server",
|
||||
Source: "github",
|
||||
ID: "testuser/build-metadata-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), buildMetadataServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
authHeader string
|
||||
requestBody interface{}
|
||||
serverID string
|
||||
serverName string
|
||||
version string
|
||||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody apiv0.ServerJSON
|
||||
statusParam string
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "successful edit with valid token and permissions",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
Status: model.StatusDeprecated,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/test-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/test-server",
|
||||
name: "successful edit with valid permissions",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Updated server description",
|
||||
Version: "1.0.0",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/editable-server",
|
||||
Source: "github",
|
||||
ID: "testuser/editable-server",
|
||||
},
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Updated server description", resp.Server.Description)
|
||||
assert.Equal(t, "io.github.testuser/editable-server", resp.Server.Name)
|
||||
assert.Equal(t, "1.0.0", resp.Server.Version)
|
||||
assert.NotNil(t, resp.Meta.Official)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful edit with status change",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Server with status change",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
statusParam: "deprecated",
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Server with status change", resp.Server.Description)
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
authHeader: "",
|
||||
requestBody: apiv0.ServerJSON{},
|
||||
serverID: testServerID,
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
expectedStatus: 422,
|
||||
authHeader: "", // No auth header
|
||||
requestBody: apiv0.ServerJSON{},
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "required header parameter is missing",
|
||||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Unauthorized",
|
||||
expectedError: "Invalid Authorization header format",
|
||||
},
|
||||
{
|
||||
name: "invalid token",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "Bearer invalid-token",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Unauthorized",
|
||||
expectedError: "Invalid or expired Registry JWT token",
|
||||
},
|
||||
{
|
||||
name: "permission denied - no edit permissions",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "Forbidden",
|
||||
},
|
||||
{
|
||||
name: "permission denied - wrong resource",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: otherServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "Forbidden",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.domdomegg/*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/nonexistent-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: "550e8400-e29b-41d4-a716-446655440999", // Non-existent ID
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Not Found",
|
||||
},
|
||||
{
|
||||
name: "validation error - invalid server name",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "invalid-name-format", // Missing namespace/name format
|
||||
Description: "Test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
serverID: testServerID,
|
||||
version: "1.0.0",
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Bad Request",
|
||||
},
|
||||
{
|
||||
name: "cannot undelete server",
|
||||
authHeader: func() string {
|
||||
cfg := &config.Config{JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c"}
|
||||
token, _ := generateTestJWTToken(cfg, auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "domdomegg",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/deleted-server",
|
||||
Description: "Trying to undelete server",
|
||||
Status: model.StatusActive,
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/domdomegg/deleted-server",
|
||||
Source: "github",
|
||||
ID: "domdomegg/deleted-server",
|
||||
name: "permission denied - no edit permissions",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"}, // Only publish, not edit
|
||||
},
|
||||
Version: "1.0.1",
|
||||
},
|
||||
serverID: deletedServerID,
|
||||
version: "1.0.0",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have edit permissions",
|
||||
},
|
||||
{
|
||||
name: "permission denied - wrong namespace",
|
||||
serverName: "io.github.otheruser/other-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"}, // Wrong namespace
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.otheruser/other-server",
|
||||
Description: "Updated test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have edit permissions",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverName: "io.github.testuser/non-existent",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/non-existent",
|
||||
Description: "Non-existent server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Server not found",
|
||||
},
|
||||
{
|
||||
name: "attempt to rename server should fail",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/renamed-server", // Different name
|
||||
Description: "Trying to rename server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Cannot rename server",
|
||||
},
|
||||
{
|
||||
name: "version in body must match URL parameter",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Version mismatch test",
|
||||
Version: "2.0.0", // Different version from URL
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Version in request body must match URL path parameter",
|
||||
},
|
||||
{
|
||||
name: "attempt to undelete server should fail",
|
||||
serverName: "io.github.testuser/deleted-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Trying to undelete server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
statusParam: "active", // Trying to change from deleted to active
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Cannot change status of deleted server",
|
||||
},
|
||||
{
|
||||
name: "successful edit of version with build metadata (URL encoded)",
|
||||
serverName: "io.github.testuser/build-metadata-server",
|
||||
version: "1.0.0+20130313144700",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/build-metadata-server",
|
||||
Description: "Updated server with build metadata",
|
||||
Version: "1.0.0+20130313144700",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/build-metadata-server",
|
||||
Source: "github",
|
||||
ID: "testuser/build-metadata-server",
|
||||
},
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Updated server with build metadata", resp.Server.Description)
|
||||
assert.Equal(t, "io.github.testuser/build-metadata-server", resp.Server.Name)
|
||||
assert.Equal(t, "1.0.0+20130313144700", resp.Server.Version)
|
||||
assert.NotNil(t, resp.Meta.Official)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
humaConfig := huma.DefaultConfig("Test API", "1.0.0")
|
||||
api := humago.New(mux, humaConfig)
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
|
||||
// Register edit endpoints
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: "bb2c6b424005acd5df47a9e2c87f446def86dd740c888ea3efb825b23f7ef47c",
|
||||
}
|
||||
v0.RegisterEditEndpoints(api, registryService, cfg)
|
||||
|
||||
// Create request body
|
||||
var requestBody []byte
|
||||
var err error
|
||||
if str, ok := tc.requestBody.(string); ok {
|
||||
requestBody = []byte(str)
|
||||
} else {
|
||||
requestBody, err = json.Marshal(tc.requestBody)
|
||||
assert.NoError(t, err)
|
||||
requestBody, err := json.Marshal(tc.requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create request URL with proper encoding
|
||||
encodedServerName := url.PathEscape(tc.serverName)
|
||||
encodedVersion := url.PathEscape(tc.version)
|
||||
requestURL := "/v0/servers/" + encodedServerName + "/versions/" + encodedVersion
|
||||
if tc.statusParam != "" {
|
||||
requestURL += "?status=" + tc.statusParam
|
||||
}
|
||||
|
||||
// Create request
|
||||
url := "/v0/servers/" + tc.serverID
|
||||
if tc.version != "" {
|
||||
url += "?version=" + tc.version
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPut, url, bytes.NewReader(requestBody))
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Set authorization header
|
||||
if tc.authHeader != "" {
|
||||
req.Header.Set("Authorization", tc.authHeader)
|
||||
} else if tc.authClaims != nil {
|
||||
// Generate valid JWT token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), *tc.authClaims)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
}
|
||||
|
||||
// Create response recorder
|
||||
// Create response recorder and execute request
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
// Call the endpoint
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check status code
|
||||
// Check response
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
// Check error message if expected
|
||||
if tc.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tc.expectedError)
|
||||
}
|
||||
|
||||
// No mock assertions needed with real service
|
||||
if tc.expectedStatus == http.StatusOK && tc.checkResult != nil {
|
||||
var response apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
tc.checkResult(t, &response)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEditServerEndpointEdgeCases(t *testing.T) {
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
|
||||
// Create registry service
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Setup test servers with different characteristics
|
||||
testServers := []struct {
|
||||
name string
|
||||
version string
|
||||
status model.Status
|
||||
}{
|
||||
{"com.example/active-server", "1.0.0", model.StatusActive},
|
||||
{"com.example/deprecated-server", "1.0.0", model.StatusDeprecated},
|
||||
{"com.example/multi-version-server", "1.0.0", model.StatusActive},
|
||||
{"com.example/multi-version-server", "2.0.0", model.StatusActive},
|
||||
}
|
||||
|
||||
for _, server := range testServers {
|
||||
_, err := registryService.CreateServer(context.Background(), &apiv0.ServerJSON{
|
||||
Name: server.name,
|
||||
Description: "Test server for editing",
|
||||
Version: server.version,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set specific status if not active
|
||||
if server.status != model.StatusActive {
|
||||
_, err = registryService.UpdateServer(context.Background(), server.name, server.version, &apiv0.ServerJSON{
|
||||
Name: server.name,
|
||||
Description: "Test server for editing",
|
||||
Version: server.version,
|
||||
}, stringPtr(string(server.status)))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterEditEndpoints(api, registryService, cfg)
|
||||
|
||||
t.Run("status transitions", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
fromStatus string
|
||||
toStatus string
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "active to deprecated",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "deprecated",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "deprecated to active",
|
||||
serverName: "com.example/deprecated-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "active",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "active to deleted",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "deleted",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "invalid status",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "invalid_status",
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "validation failed",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Name: tt.serverName,
|
||||
Description: "Status transition test",
|
||||
Version: tt.version,
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(tt.serverName)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/" + tt.version + "?status=" + tt.toStatus
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
if tt.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tt.expectedError)
|
||||
}
|
||||
|
||||
if tt.expectedStatus == http.StatusOK {
|
||||
var response apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.Status(tt.toStatus), response.Meta.Official.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("URL encoding edge cases", func(t *testing.T) {
|
||||
// Create server with special characters
|
||||
specialServerName := "io.dots.and-dashes/server_with_underscores"
|
||||
_, err := registryService.CreateServer(context.Background(), &apiv0.ServerJSON{
|
||||
Name: specialServerName,
|
||||
Description: "Server with special characters",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Name: specialServerName,
|
||||
Description: "Updated server with special chars",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(specialServerName)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var response apiv0.ServerResponse
|
||||
err = json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, specialServerName, response.Server.Name)
|
||||
assert.Equal(t, "Updated server with special chars", response.Server.Description)
|
||||
})
|
||||
|
||||
t.Run("version-specific editing", func(t *testing.T) {
|
||||
// Test editing a specific version of a multi-version server
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Name: "com.example/multi-version-server",
|
||||
Description: "Updated v1.0.0 specifically",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape("com.example/multi-version-server")
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var response apiv0.ServerResponse
|
||||
err = json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Updated v1.0.0 specifically", response.Server.Description)
|
||||
assert.Equal(t, "1.0.0", response.Server.Version)
|
||||
|
||||
// Verify the other version wasn't affected
|
||||
otherVersion, err := registryService.GetServerByNameAndVersion(context.Background(), "com.example/multi-version-server", "2.0.0")
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, "Updated v1.0.0 specifically", otherVersion.Server.Description)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper function
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
|
@ -33,7 +33,7 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
|
|||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *PublishServerInput) (*Response[apiv0.ServerJSON], error) {
|
||||
}, func(ctx context.Context, input *PublishServerInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
|
|
@ -54,13 +54,13 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
|
|||
}
|
||||
|
||||
// Publish the server with extensions
|
||||
publishedServer, err := registry.Publish(input.Body)
|
||||
publishedServer, err := registry.CreateServer(ctx, &input.Body)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Failed to publish server", err)
|
||||
}
|
||||
|
||||
// Return the published server in flattened format
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
// Return the published server response with metadata
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *publishedServer,
|
||||
}, nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -90,12 +90,13 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Version)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Server.Version)
|
||||
assert.NotNil(t, response.Meta.Official)
|
||||
})
|
||||
|
||||
t.Run("successful publish with none auth (no prefix)", func(t *testing.T) {
|
||||
|
|
@ -132,11 +133,12 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.NotNil(t, response.Meta.Official)
|
||||
})
|
||||
|
||||
t.Run("publish fails with missing authorization header", func(t *testing.T) {
|
||||
|
|
@ -220,7 +222,6 @@ func TestPublishIntegration(t *testing.T) {
|
|||
Name: "io.github.domdomegg/airtable-mcp-server",
|
||||
Description: "A test server with MCPB package",
|
||||
Version: "1.7.2",
|
||||
Status: model.StatusActive,
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: model.RegistryTypeMCPB,
|
||||
|
|
@ -256,13 +257,14 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Version)
|
||||
assert.Len(t, response.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Packages[0].RegistryType)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Server.Version)
|
||||
assert.NotNil(t, response.Meta.Official)
|
||||
assert.Len(t, response.Server.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Server.Packages[0].RegistryType)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -124,14 +124,14 @@ func TestPublishRegistryValidation(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerJSON
|
||||
var response apiv0.ServerResponse
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Version)
|
||||
assert.Len(t, response.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Packages[0].RegistryType)
|
||||
assert.Equal(t, publishReq.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Version, response.Server.Version)
|
||||
assert.Len(t, response.Server.Packages, 1)
|
||||
assert.Equal(t, model.RegistryTypeMCPB, response.Server.Packages[0].RegistryType)
|
||||
})
|
||||
|
||||
t.Run("publish fails when second package fails npm validation", func(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -192,7 +192,7 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
ID: "example/test-server-existing",
|
||||
},
|
||||
}
|
||||
_, _ = registry.Publish(existingServer)
|
||||
_, _ = registry.CreateServer(context.Background(), &existingServer)
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "invalid version: cannot publish duplicate version",
|
||||
|
|
|
|||
|
|
@ -4,18 +4,20 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/google/uuid"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
)
|
||||
|
||||
const errRecordNotFound = "record not found"
|
||||
|
||||
// ListServersInput represents the input for listing servers
|
||||
type ListServersInput struct {
|
||||
Cursor string `query:"cursor" doc:"Pagination cursor (UUID)" format:"uuid" required:"false" example:"550e8400-e29b-41d4-a716-446655440000"`
|
||||
Cursor string `query:"cursor" doc:"Pagination cursor" required:"false" example:"server-cursor-123"`
|
||||
Limit int `query:"limit" doc:"Number of items per page" default:"30" minimum:"1" maximum:"100" example:"50"`
|
||||
UpdatedSince string `query:"updated_since" doc:"Filter servers updated since timestamp (RFC3339 datetime)" required:"false" example:"2025-08-07T13:15:04.280Z"`
|
||||
Search string `query:"search" doc:"Search servers by name (substring match)" required:"false" example:"filesystem"`
|
||||
|
|
@ -24,16 +26,22 @@ type ListServersInput struct {
|
|||
|
||||
// ServerDetailInput represents the input for getting server details
|
||||
type ServerDetailInput struct {
|
||||
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
Version string `query:"version" doc:"Specific version to retrieve (e.g., '1.0.0'). If not specified, returns latest version." required:"false" example:"1.0.0"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
}
|
||||
|
||||
// ServerVersionDetailInput represents the input for getting a specific version
|
||||
type ServerVersionDetailInput struct {
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded server version" example:"1.0.0"`
|
||||
}
|
||||
|
||||
// ServerVersionsInput represents the input for listing all versions of a server
|
||||
type ServerVersionsInput struct {
|
||||
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
}
|
||||
|
||||
// RegisterServersEndpoints registers all server-related endpoints
|
||||
//nolint:cyclop // Multiple endpoint registrations are inherently complex
|
||||
func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
||||
// List servers endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
|
|
@ -43,15 +51,7 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
Summary: "List MCP servers",
|
||||
Description: "Get a paginated list of MCP servers from the registry",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ListServersInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// Validate cursor if provided
|
||||
if input.Cursor != "" {
|
||||
_, err := uuid.Parse(input.Cursor)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid cursor parameter")
|
||||
}
|
||||
}
|
||||
|
||||
}, func(ctx context.Context, input *ListServersInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// Build filter from input parameters
|
||||
filter := &database.ServerFilter{}
|
||||
|
||||
|
|
@ -83,14 +83,20 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
}
|
||||
|
||||
// Get paginated results with filtering
|
||||
servers, nextCursor, err := registry.List(filter, input.Cursor, input.Limit)
|
||||
servers, nextCursor, err := registry.ListServers(ctx, filter, input.Cursor, input.Limit)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("Failed to get registry list", err)
|
||||
}
|
||||
|
||||
// Convert []*ServerResponse to []ServerResponse
|
||||
serverValues := make([]apiv0.ServerResponse, len(servers))
|
||||
for i, server := range servers {
|
||||
serverValues[i] = *server
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerListResponse]{
|
||||
Body: apiv0.ServerListResponse{
|
||||
Servers: servers,
|
||||
Servers: serverValues,
|
||||
Metadata: apiv0.Metadata{
|
||||
NextCursor: nextCursor,
|
||||
Count: len(servers),
|
||||
|
|
@ -99,36 +105,67 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
}, nil
|
||||
})
|
||||
|
||||
// Get server details endpoint
|
||||
// Get server details endpoint (latest version)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-server",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers/{server_id}",
|
||||
Path: "/v0/servers/{serverName}",
|
||||
Summary: "Get MCP server details",
|
||||
Description: "Get detailed information about a specific MCP server. Returns the latest version by default, or a specific version if the 'version' query parameter is provided.",
|
||||
Description: "Get detailed information about the latest version of a specific MCP server.",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ServerDetailInput) (*Response[apiv0.ServerJSON], error) {
|
||||
// Get the server details from the registry service
|
||||
var serverDetail *apiv0.ServerJSON
|
||||
var err error
|
||||
|
||||
if input.Version != "" {
|
||||
// Get specific version by server_id and version
|
||||
serverDetail, err = registry.GetByServerIDAndVersion(input.ServerID, input.Version)
|
||||
} else {
|
||||
// Get latest version by server_id
|
||||
serverDetail, err = registry.GetByServerID(input.ServerID)
|
||||
}, func(ctx context.Context, input *ServerDetailInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// Get latest version by server name
|
||||
serverResponse, err := registry.GetServerByName(ctx, serverName)
|
||||
if err != nil {
|
||||
if err.Error() == "record not found" || errors.Is(err, database.ErrNotFound) {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server details", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
Body: *serverDetail,
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *serverResponse,
|
||||
}, nil
|
||||
})
|
||||
|
||||
// Get specific server version endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-server-version",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers/{serverName}/versions/{version}",
|
||||
Summary: "Get specific MCP server version",
|
||||
Description: "Get detailed information about a specific version of an MCP server.",
|
||||
Tags: []string{"servers"},
|
||||
}, func(ctx context.Context, input *ServerVersionDetailInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// URL-decode the version
|
||||
version, err := url.PathUnescape(input.Version)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid version encoding", err)
|
||||
}
|
||||
|
||||
// Get specific version by server name and version
|
||||
serverResponse, err := registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
if err != nil {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server details", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *serverResponse,
|
||||
}, nil
|
||||
})
|
||||
|
||||
|
|
@ -136,23 +173,35 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-server-versions",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers/{server_id}/versions",
|
||||
Path: "/v0/servers/{serverName}/versions",
|
||||
Summary: "Get all versions of an MCP server",
|
||||
Description: "Get all available versions for a specific MCP server",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ServerVersionsInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// Get all versions for this server
|
||||
servers, err := registry.GetAllVersionsByServerID(input.ServerID)
|
||||
}, func(ctx context.Context, input *ServerVersionsInput) (*Response[apiv0.ServerListResponse], error) {
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
if err.Error() == "record not found" {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// Get all versions for this server
|
||||
servers, err := registry.GetAllVersionsByServerName(ctx, serverName)
|
||||
if err != nil {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server versions", err)
|
||||
}
|
||||
|
||||
// Convert []*ServerResponse to []ServerResponse
|
||||
serverValues := make([]apiv0.ServerResponse, len(servers))
|
||||
for i, server := range servers {
|
||||
serverValues[i] = *server
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerListResponse]{
|
||||
Body: apiv0.ServerListResponse{
|
||||
Servers: servers,
|
||||
Servers: serverValues,
|
||||
Metadata: apiv0.Metadata{
|
||||
Count: len(servers),
|
||||
},
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
|
@ -22,7 +23,7 @@ import (
|
|||
|
||||
func TestPrometheusHandler(t *testing.T) {
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
server, err := registryService.Publish(apiv0.ServerJSON{
|
||||
server, err := registryService.CreateServer(context.Background(), &apiv0.ServerJSON{
|
||||
Name: "io.github.example/test-server",
|
||||
Description: "Test server detail",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -50,8 +51,8 @@ func TestPrometheusHandler(t *testing.T) {
|
|||
// Add /metrics for Prometheus metrics using promhttp
|
||||
mux.Handle("/metrics", metrics.PrometheusHandler())
|
||||
|
||||
// Create request
|
||||
url := "/v0/servers/" + server.Meta.Official.ServerID
|
||||
// Create request - using new name-based API
|
||||
url := "/v0/servers/" + url.PathEscape(server.Server.Name)
|
||||
req := httptest.NewRequest(http.MethodGet, url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
|
@ -76,5 +77,5 @@ func TestPrometheusHandler(t *testing.T) {
|
|||
// Check if the response body contains expected metrics
|
||||
assert.Contains(t, body, "mcp_registry_http_request_duration_bucket")
|
||||
assert.Contains(t, body, "mcp_registry_http_requests_total")
|
||||
assert.Contains(t, body, "path=\"/v0/servers/{server_id}\"")
|
||||
assert.Contains(t, body, "path=\"/v0/servers/{serverName}\"")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,20 +31,28 @@ type ServerFilter struct {
|
|||
|
||||
// Database defines the interface for database operations
|
||||
type Database interface {
|
||||
// Retrieve server entries with optional filtering
|
||||
List(ctx context.Context, tx pgx.Tx, filter *ServerFilter, cursor string, limit int) ([]*apiv0.ServerJSON, string, error)
|
||||
// Retrieve a single server by its version ID
|
||||
GetByVersionID(ctx context.Context, tx pgx.Tx, versionID string) (*apiv0.ServerJSON, error)
|
||||
// Retrieve latest version of a server by server ID
|
||||
GetByServerID(ctx context.Context, tx pgx.Tx, serverID string) (*apiv0.ServerJSON, error)
|
||||
// Retrieve specific version of a server by server ID and version
|
||||
GetByServerIDAndVersion(ctx context.Context, tx pgx.Tx, serverID string, version string) (*apiv0.ServerJSON, error)
|
||||
// Retrieve all versions of a server by server ID
|
||||
GetAllVersionsByServerID(ctx context.Context, tx pgx.Tx, serverID string) ([]*apiv0.ServerJSON, error)
|
||||
// CreateServer inserts a new server version
|
||||
CreateServer(ctx context.Context, tx pgx.Tx, newServer *apiv0.ServerJSON) (*apiv0.ServerJSON, error)
|
||||
// CreateServer inserts a new server version with official metadata
|
||||
CreateServer(ctx context.Context, tx pgx.Tx, serverJSON *apiv0.ServerJSON, officialMeta *apiv0.RegistryExtensions) (*apiv0.ServerResponse, error)
|
||||
// UpdateServer updates an existing server record
|
||||
UpdateServer(ctx context.Context, tx pgx.Tx, id string, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error)
|
||||
UpdateServer(ctx context.Context, tx pgx.Tx, serverName, version string, serverJSON *apiv0.ServerJSON) (*apiv0.ServerResponse, error)
|
||||
// SetServerStatus updates the status of a specific server version
|
||||
SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status string) (*apiv0.ServerResponse, error)
|
||||
// ListServers retrieve server entries with optional filtering
|
||||
ListServers(ctx context.Context, tx pgx.Tx, filter *ServerFilter, cursor string, limit int) ([]*apiv0.ServerResponse, string, error)
|
||||
// GetServerByName retrieve a single server by its name
|
||||
GetServerByName(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error)
|
||||
// GetServerByNameAndVersion retrieve specific version of a server by server name and version
|
||||
GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string) (*apiv0.ServerResponse, error)
|
||||
// GetAllVersionsByServerName retrieve all versions of a server by server name
|
||||
GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string) ([]*apiv0.ServerResponse, error)
|
||||
// GetCurrentLatestVersion retrieve the current latest version of a server by server name
|
||||
GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error)
|
||||
// CountServerVersions count the number of versions for a server
|
||||
CountServerVersions(ctx context.Context, tx pgx.Tx, serverName string) (int, error)
|
||||
// CheckVersionExists check if a specific version exists for a server
|
||||
CheckVersionExists(ctx context.Context, tx pgx.Tx, serverName, version string) (bool, error)
|
||||
// UnmarkAsLatest marks the current latest version of a server as no longer latest
|
||||
UnmarkAsLatest(ctx context.Context, tx pgx.Tx, serverName string) error
|
||||
// AcquirePublishLock acquires an exclusive advisory lock for publishing a server
|
||||
// This prevents race conditions when multiple versions are published concurrently
|
||||
AcquirePublishLock(ctx context.Context, tx pgx.Tx, serverName string) error
|
||||
|
|
|
|||
143
internal/database/migrations/008_separate_official_metadata.sql
Normal file
143
internal/database/migrations/008_separate_official_metadata.sql
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
-- Separate official metadata from JSON to dedicated columns for better performance and consistency
|
||||
-- This migration transforms the database from JSON-heavy to columnar structure for registry-managed data
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Add new columns for official metadata and core identifiers
|
||||
ALTER TABLE servers ADD COLUMN server_name VARCHAR(255);
|
||||
ALTER TABLE servers ADD COLUMN version VARCHAR(255);
|
||||
ALTER TABLE servers ADD COLUMN status VARCHAR(50);
|
||||
ALTER TABLE servers ADD COLUMN published_at TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE servers ADD COLUMN updated_at TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE servers ADD COLUMN is_latest BOOLEAN;
|
||||
|
||||
-- Create a function to migrate existing data from JSON to columns
|
||||
CREATE OR REPLACE FUNCTION migrate_official_metadata()
|
||||
RETURNS VOID AS $$
|
||||
DECLARE
|
||||
rec RECORD;
|
||||
official_meta JSONB;
|
||||
updated_value JSONB;
|
||||
server_meta JSONB;
|
||||
publisher_provided JSONB;
|
||||
BEGIN
|
||||
-- Iterate through all existing records
|
||||
FOR rec IN SELECT version_id, value FROM servers ORDER BY version_id LOOP
|
||||
-- Extract core identifiers
|
||||
UPDATE servers
|
||||
SET
|
||||
server_name = rec.value->>'name',
|
||||
version = rec.value->>'version'
|
||||
WHERE version_id = rec.version_id;
|
||||
|
||||
-- Extract official metadata from nested JSON structure
|
||||
official_meta := rec.value->'_meta'->'io.modelcontextprotocol.registry/official';
|
||||
|
||||
IF official_meta IS NOT NULL THEN
|
||||
-- Update columns with extracted metadata
|
||||
UPDATE servers
|
||||
SET
|
||||
status = (official_meta->>'status')::VARCHAR(50),
|
||||
published_at = (official_meta->>'publishedAt')::TIMESTAMP WITH TIME ZONE,
|
||||
updated_at = (official_meta->>'updatedAt')::TIMESTAMP WITH TIME ZONE,
|
||||
is_latest = (official_meta->>'isLatest')::BOOLEAN
|
||||
WHERE version_id = rec.version_id;
|
||||
ELSE
|
||||
-- Handle records without official metadata (set defaults)
|
||||
UPDATE servers
|
||||
SET
|
||||
status = COALESCE((rec.value->>'status'), 'active'),
|
||||
published_at = NOW(),
|
||||
updated_at = NOW(),
|
||||
is_latest = true
|
||||
WHERE version_id = rec.version_id;
|
||||
END IF;
|
||||
|
||||
-- Clean up the JSON: remove status field and official metadata
|
||||
updated_value := rec.value - 'status';
|
||||
|
||||
-- Reconstruct _meta with only publisher-provided data
|
||||
publisher_provided := rec.value->'_meta'->'io.modelcontextprotocol.registry/publisher-provided';
|
||||
|
||||
IF publisher_provided IS NOT NULL THEN
|
||||
server_meta := jsonb_build_object('io.modelcontextprotocol.registry/publisher-provided', publisher_provided);
|
||||
updated_value := jsonb_set(updated_value, '{_meta}', server_meta);
|
||||
ELSE
|
||||
-- Remove _meta entirely if no publisher-provided data
|
||||
updated_value := updated_value - '_meta';
|
||||
END IF;
|
||||
|
||||
-- Update the JSON with cleaned structure (keeping name and version for immutable server.json)
|
||||
UPDATE servers
|
||||
SET value = updated_value
|
||||
WHERE version_id = rec.version_id;
|
||||
END LOOP;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Execute the migration
|
||||
SELECT migrate_official_metadata();
|
||||
|
||||
-- Drop the migration function
|
||||
DROP FUNCTION migrate_official_metadata();
|
||||
|
||||
-- Make the new columns NOT NULL now that all records have values
|
||||
ALTER TABLE servers ALTER COLUMN server_name SET NOT NULL;
|
||||
ALTER TABLE servers ALTER COLUMN version SET NOT NULL;
|
||||
ALTER TABLE servers ALTER COLUMN status SET NOT NULL;
|
||||
ALTER TABLE servers ALTER COLUMN published_at SET NOT NULL;
|
||||
ALTER TABLE servers ALTER COLUMN is_latest SET NOT NULL;
|
||||
|
||||
-- Drop the old primary key constraint
|
||||
ALTER TABLE servers DROP CONSTRAINT servers_pkey;
|
||||
|
||||
-- Create new composite primary key using name + version (natural key)
|
||||
ALTER TABLE servers ADD CONSTRAINT servers_pkey PRIMARY KEY (server_name, version);
|
||||
|
||||
-- Drop the old version_id column since we're using name-based keys now
|
||||
ALTER TABLE servers DROP COLUMN version_id;
|
||||
|
||||
-- Drop old indexes that used JSON paths and UUIDs
|
||||
DROP INDEX IF EXISTS idx_servers_version_id;
|
||||
DROP INDEX IF EXISTS idx_servers_name_latest;
|
||||
DROP INDEX IF EXISTS idx_servers_updated_at;
|
||||
DROP INDEX IF EXISTS idx_servers_remotes;
|
||||
DROP INDEX IF EXISTS idx_unique_server_version;
|
||||
DROP INDEX IF EXISTS idx_unique_latest_version;
|
||||
|
||||
-- Create new efficient indexes on the dedicated columns
|
||||
CREATE INDEX idx_servers_name ON servers (server_name);
|
||||
CREATE INDEX idx_servers_name_version ON servers (server_name, version);
|
||||
CREATE INDEX idx_servers_name_latest ON servers (server_name, is_latest) WHERE is_latest = true;
|
||||
CREATE INDEX idx_servers_status ON servers (status);
|
||||
CREATE INDEX idx_servers_published_at ON servers (published_at DESC);
|
||||
CREATE INDEX idx_servers_updated_at ON servers (updated_at DESC) WHERE updated_at IS NOT NULL;
|
||||
|
||||
-- Ensure only one version per server can be marked as latest
|
||||
CREATE UNIQUE INDEX idx_unique_latest_per_server
|
||||
ON servers (server_name)
|
||||
WHERE is_latest = true;
|
||||
|
||||
-- Create GIN index for remaining JSON queries (remotes, packages, etc.)
|
||||
CREATE INDEX idx_servers_json_remotes ON servers USING GIN((value->'remotes'));
|
||||
CREATE INDEX idx_servers_json_packages ON servers USING GIN((value->'packages'));
|
||||
|
||||
-- Update $schema field to latest version for all entries
|
||||
UPDATE servers
|
||||
SET value = jsonb_set(value, '{$schema}', '"https://static.modelcontextprotocol.io/schemas/2025-09-29/server.schema.json"')
|
||||
WHERE value ? '$schema' AND value IS NOT NULL;
|
||||
|
||||
-- Add check constraints for data integrity
|
||||
ALTER TABLE servers ADD CONSTRAINT check_status_valid
|
||||
CHECK (status IN ('active', 'deprecated', 'deleted'));
|
||||
|
||||
ALTER TABLE servers ADD CONSTRAINT check_server_name_format
|
||||
CHECK (server_name ~ '^[a-zA-Z0-9][a-zA-Z0-9.-]*[a-zA-Z0-9]/[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$');
|
||||
|
||||
ALTER TABLE servers ADD CONSTRAINT check_version_not_empty
|
||||
CHECK (length(trim(version)) > 0);
|
||||
|
||||
ALTER TABLE servers ADD CONSTRAINT check_published_at_reasonable
|
||||
CHECK (published_at >= '2020-01-01'::timestamp AND published_at <= NOW() + interval '1 day');
|
||||
|
||||
COMMIT;
|
||||
|
|
@ -9,12 +9,12 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// PostgreSQL is an implementation of the Database interface using PostgreSQL
|
||||
|
|
@ -79,14 +79,13 @@ func NewPostgreSQL(ctx context.Context, connectionURI string) (*PostgreSQL, erro
|
|||
}, nil
|
||||
}
|
||||
|
||||
//nolint:cyclop // Database filtering logic is inherently complex but clear
|
||||
func (db *PostgreSQL) List(
|
||||
func (db *PostgreSQL) ListServers(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
filter *ServerFilter,
|
||||
cursor string,
|
||||
limit int,
|
||||
) ([]*apiv0.ServerJSON, string, error) {
|
||||
) ([]*apiv0.ServerResponse, string, error) {
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
|
|
@ -95,15 +94,15 @@ func (db *PostgreSQL) List(
|
|||
return nil, "", ctx.Err()
|
||||
}
|
||||
|
||||
// Build WHERE clause for filtering
|
||||
// Build WHERE clause for filtering using dedicated columns
|
||||
var whereConditions []string
|
||||
args := []any{}
|
||||
argIndex := 1
|
||||
|
||||
// Add filters using JSON operators
|
||||
// Add filters using dedicated columns for better performance
|
||||
if filter != nil {
|
||||
if filter.Name != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("value->>'name' = $%d", argIndex))
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("server_name = $%d", argIndex))
|
||||
args = append(args, *filter.Name)
|
||||
argIndex++
|
||||
}
|
||||
|
|
@ -113,35 +112,45 @@ func (db *PostgreSQL) List(
|
|||
argIndex++
|
||||
}
|
||||
if filter.UpdatedSince != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("(value->'_meta'->'io.modelcontextprotocol.registry/official'->>'updatedAt')::timestamp > $%d", argIndex))
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("updated_at > $%d", argIndex))
|
||||
args = append(args, *filter.UpdatedSince)
|
||||
argIndex++
|
||||
}
|
||||
if filter.SubstringName != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("value->>'name' ILIKE $%d", argIndex))
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("server_name ILIKE $%d", argIndex))
|
||||
args = append(args, "%"+*filter.SubstringName+"%")
|
||||
argIndex++
|
||||
}
|
||||
if filter.Version != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("(value->'version_detail'->>'version') = $%d", argIndex))
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("version = $%d", argIndex))
|
||||
args = append(args, *filter.Version)
|
||||
argIndex++
|
||||
}
|
||||
if filter.IsLatest != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("(value->'_meta'->'io.modelcontextprotocol.registry/official'->>'isLatest')::boolean = $%d", argIndex))
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("is_latest = $%d", argIndex))
|
||||
args = append(args, *filter.IsLatest)
|
||||
argIndex++
|
||||
}
|
||||
}
|
||||
|
||||
// Add cursor pagination using primary key version_id
|
||||
// Add cursor pagination using compound serverName:version cursor
|
||||
if cursor != "" {
|
||||
if _, err := uuid.Parse(cursor); err != nil {
|
||||
return nil, "", fmt.Errorf("invalid cursor format: %w", err)
|
||||
// Parse cursor format: "serverName:version"
|
||||
parts := strings.SplitN(cursor, ":", 2)
|
||||
if len(parts) == 2 {
|
||||
cursorServerName := parts[0]
|
||||
cursorVersion := parts[1]
|
||||
|
||||
// Use compound condition: (server_name > cursor_name) OR (server_name = cursor_name AND version > cursor_version)
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("(server_name > $%d OR (server_name = $%d AND version > $%d))", argIndex, argIndex+1, argIndex+2))
|
||||
args = append(args, cursorServerName, cursorServerName, cursorVersion)
|
||||
argIndex += 3
|
||||
} else {
|
||||
// Fallback for malformed cursor - treat as server name only for backwards compatibility
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("server_name > $%d", argIndex))
|
||||
args = append(args, cursor)
|
||||
argIndex++
|
||||
}
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("version_id > $%d", argIndex))
|
||||
args = append(args, cursor)
|
||||
argIndex++
|
||||
}
|
||||
|
||||
// Build the WHERE clause
|
||||
|
|
@ -150,12 +159,12 @@ func (db *PostgreSQL) List(
|
|||
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
|
||||
}
|
||||
|
||||
// Simple query on servers table
|
||||
// Query servers table with hybrid column/JSON data
|
||||
query := fmt.Sprintf(`
|
||||
SELECT value
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
%s
|
||||
ORDER BY version_id
|
||||
ORDER BY server_name, version
|
||||
LIMIT $%d
|
||||
`, whereClause, argIndex)
|
||||
args = append(args, limit)
|
||||
|
|
@ -166,170 +175,202 @@ func (db *PostgreSQL) List(
|
|||
}
|
||||
defer rows.Close()
|
||||
|
||||
var results []*apiv0.ServerJSON
|
||||
var results []*apiv0.ServerResponse
|
||||
for rows.Next() {
|
||||
var serverName, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
|
||||
err := rows.Scan(&valueJSON)
|
||||
err := rows.Scan(&serverName, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to scan server row: %w", err)
|
||||
}
|
||||
|
||||
// Parse the complete ServerJSON from JSONB
|
||||
// Parse the ServerJSON from JSONB
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
|
||||
return nil, "", fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
results = append(results, &serverJSON)
|
||||
// Build ServerResponse with separated metadata
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
results = append(results, serverResponse)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, "", fmt.Errorf("error iterating rows: %w", err)
|
||||
}
|
||||
|
||||
// Determine next cursor using registry metadata VersionID
|
||||
// Determine next cursor using compound serverName:version format
|
||||
nextCursor := ""
|
||||
if len(results) > 0 && len(results) >= limit {
|
||||
lastResult := results[len(results)-1]
|
||||
if lastResult.Meta != nil && lastResult.Meta.Official != nil {
|
||||
nextCursor = lastResult.Meta.Official.VersionID
|
||||
}
|
||||
nextCursor = lastResult.Server.Name + ":" + lastResult.Server.Version
|
||||
}
|
||||
|
||||
return results, nextCursor, nil
|
||||
}
|
||||
|
||||
func (db *PostgreSQL) GetByVersionID(ctx context.Context, tx pgx.Tx, versionID string) (*apiv0.ServerJSON, error) {
|
||||
// GetServerByName retrieves the latest version of a server by server name
|
||||
func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT value
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
WHERE version_id = $1
|
||||
`
|
||||
|
||||
var valueJSON []byte
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, versionID).Scan(&valueJSON)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get server by ID: %w", err)
|
||||
}
|
||||
|
||||
// Parse the complete ServerJSON from JSONB
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
return &serverJSON, nil
|
||||
}
|
||||
|
||||
// GetByServerID retrieves the latest version of a server by server ID
|
||||
func (db *PostgreSQL) GetByServerID(ctx context.Context, tx pgx.Tx, serverID string) (*apiv0.ServerJSON, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT value
|
||||
FROM servers
|
||||
WHERE (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'serverId') = $1 AND (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'isLatest')::boolean = true
|
||||
ORDER BY (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'publishedAt')::timestamp DESC
|
||||
WHERE server_name = $1 AND is_latest = true
|
||||
ORDER BY published_at DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
var name, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, serverID).Scan(&valueJSON)
|
||||
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, serverName).Scan(&name, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get server by server ID: %w", err)
|
||||
return nil, fmt.Errorf("failed to get server by name: %w", err)
|
||||
}
|
||||
|
||||
// Parse the complete ServerJSON from JSONB
|
||||
// Parse the ServerJSON from JSONB
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
return &serverJSON, nil
|
||||
// Build ServerResponse with separated metadata
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return serverResponse, nil
|
||||
}
|
||||
|
||||
// GetByServerIDAndVersion retrieves a specific version of a server by server ID and version
|
||||
func (db *PostgreSQL) GetByServerIDAndVersion(ctx context.Context, tx pgx.Tx, serverID string, version string) (*apiv0.ServerJSON, error) {
|
||||
// GetServerByNameAndVersion retrieves a specific version of a server by server name and version
|
||||
func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT value
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
WHERE (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'serverId') = $1 AND value->>'version' = $2
|
||||
WHERE server_name = $1 AND version = $2
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
var name, vers, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, serverID, version).Scan(&valueJSON)
|
||||
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, serverName, version).Scan(&name, &vers, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get server by server ID and version: %w", err)
|
||||
return nil, fmt.Errorf("failed to get server by name and version: %w", err)
|
||||
}
|
||||
|
||||
// Parse the complete ServerJSON from JSONB
|
||||
// Parse the ServerJSON from JSONB
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
return &serverJSON, nil
|
||||
// Build ServerResponse with separated metadata
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return serverResponse, nil
|
||||
}
|
||||
|
||||
// GetAllVersionsByServerID retrieves all versions of a server by server ID
|
||||
func (db *PostgreSQL) GetAllVersionsByServerID(ctx context.Context, tx pgx.Tx, serverID string) ([]*apiv0.ServerJSON, error) {
|
||||
// GetAllVersionsByServerName retrieves all versions of a server by server name
|
||||
func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string) ([]*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT value
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
WHERE (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'serverId') = $1
|
||||
ORDER BY (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'publishedAt')::timestamp DESC
|
||||
WHERE server_name = $1
|
||||
ORDER BY published_at DESC
|
||||
`
|
||||
|
||||
rows, err := db.getExecutor(tx).Query(ctx, query, serverID)
|
||||
rows, err := db.getExecutor(tx).Query(ctx, query, serverName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query server versions: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var results []*apiv0.ServerJSON
|
||||
var results []*apiv0.ServerResponse
|
||||
for rows.Next() {
|
||||
var name, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
|
||||
err := rows.Scan(&valueJSON)
|
||||
err := rows.Scan(&name, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to scan server row: %w", err)
|
||||
}
|
||||
|
||||
// Parse the complete ServerJSON from JSONB
|
||||
// Parse the ServerJSON from JSONB
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
results = append(results, &serverJSON)
|
||||
// Build ServerResponse with separated metadata
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
results = append(results, serverResponse)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
|
|
@ -343,77 +384,163 @@ func (db *PostgreSQL) GetAllVersionsByServerID(ctx context.Context, tx pgx.Tx, s
|
|||
return results, nil
|
||||
}
|
||||
|
||||
// CreateServer inserts a new server version
|
||||
func (db *PostgreSQL) CreateServer(ctx context.Context, tx pgx.Tx, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
// CreateServer inserts a new server version with official metadata
|
||||
func (db *PostgreSQL) CreateServer(ctx context.Context, tx pgx.Tx, serverJSON *apiv0.ServerJSON, officialMeta *apiv0.RegistryExtensions) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
// Get the IDs from the registry metadata
|
||||
if server.Meta == nil || server.Meta.Official == nil {
|
||||
return nil, fmt.Errorf("server must have registry metadata with ServerID and VersionID")
|
||||
// Validate inputs
|
||||
if serverJSON == nil || officialMeta == nil {
|
||||
return nil, fmt.Errorf("serverJSON and officialMeta are required")
|
||||
}
|
||||
|
||||
versionID := server.Meta.Official.VersionID
|
||||
if versionID == "" {
|
||||
return nil, fmt.Errorf("server must have VersionID in registry metadata")
|
||||
if serverJSON.Name == "" || serverJSON.Version == "" {
|
||||
return nil, fmt.Errorf("server name and version are required")
|
||||
}
|
||||
|
||||
// Marshal the complete server to JSONB
|
||||
valueJSON, err := json.Marshal(server)
|
||||
// Marshal the ServerJSON to JSONB
|
||||
valueJSON, err := json.Marshal(serverJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
// Insert the new version
|
||||
// Insert the new server version using composite primary key
|
||||
insertQuery := `
|
||||
INSERT INTO servers (version_id, value)
|
||||
VALUES ($1, $2)
|
||||
INSERT INTO servers (server_name, version, status, published_at, updated_at, is_latest, value)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
`
|
||||
|
||||
_, err = db.getExecutor(tx).Exec(ctx, insertQuery, versionID, valueJSON)
|
||||
_, err = db.getExecutor(tx).Exec(ctx, insertQuery,
|
||||
serverJSON.Name,
|
||||
serverJSON.Version,
|
||||
string(officialMeta.Status),
|
||||
officialMeta.PublishedAt,
|
||||
officialMeta.UpdatedAt,
|
||||
officialMeta.IsLatest,
|
||||
valueJSON,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to insert server: %w", err)
|
||||
}
|
||||
|
||||
return server, nil
|
||||
// Return the complete ServerResponse
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: *serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: officialMeta,
|
||||
},
|
||||
}
|
||||
|
||||
return serverResponse, nil
|
||||
}
|
||||
|
||||
// UpdateServer updates an existing server record with new server details
|
||||
func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, id string, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, serverName, version string, serverJSON *apiv0.ServerJSON) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
// Validate that meta structure exists and VersionID matches path
|
||||
if server.Meta == nil || server.Meta.Official == nil || server.Meta.Official.VersionID != id {
|
||||
return nil, fmt.Errorf("%w: io.modelcontextprotocol.registry/official.version_id must match path id (%s)", ErrInvalidInput, id)
|
||||
// Validate inputs
|
||||
if serverJSON == nil {
|
||||
return nil, fmt.Errorf("serverJSON is required")
|
||||
}
|
||||
|
||||
// Marshal updated server
|
||||
valueJSON, err := json.Marshal(server)
|
||||
// Ensure the serverJSON matches the provided serverName and version
|
||||
if serverJSON.Name != serverName || serverJSON.Version != version {
|
||||
return nil, fmt.Errorf("%w: server name and version in JSON must match parameters", ErrInvalidInput)
|
||||
}
|
||||
|
||||
// Marshal updated ServerJSON
|
||||
valueJSON, err := json.Marshal(serverJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal updated server: %w", err)
|
||||
}
|
||||
|
||||
// Update the complete server record using version_id
|
||||
// Update only the JSON data (keep existing metadata columns)
|
||||
query := `
|
||||
UPDATE servers
|
||||
SET value = $1
|
||||
WHERE version_id = $2
|
||||
UPDATE servers
|
||||
SET value = $1, updated_at = NOW()
|
||||
WHERE server_name = $2 AND version = $3
|
||||
RETURNING server_name, version, status, published_at, updated_at, is_latest
|
||||
`
|
||||
|
||||
result, err := db.getExecutor(tx).Exec(ctx, query, valueJSON, id)
|
||||
var name, vers, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
|
||||
err = db.getExecutor(tx).QueryRow(ctx, query, valueJSON, serverName, version).Scan(&name, &vers, &status, &publishedAt, &updatedAt, &isLatest)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to update server: %w", err)
|
||||
}
|
||||
|
||||
if result.RowsAffected() == 0 {
|
||||
return nil, ErrNotFound
|
||||
// Return the updated ServerResponse
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: *serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return server, nil
|
||||
return serverResponse, nil
|
||||
}
|
||||
|
||||
// SetServerStatus updates the status of a specific server version
|
||||
func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status string) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
// Update the status column
|
||||
query := `
|
||||
UPDATE servers
|
||||
SET status = $1, updated_at = NOW()
|
||||
WHERE server_name = $2 AND version = $3
|
||||
RETURNING server_name, version, status, value, published_at, updated_at, is_latest
|
||||
`
|
||||
|
||||
var name, vers, currentStatus string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, status, serverName, version).Scan(&name, &vers, ¤tStatus, &valueJSON, &publishedAt, &updatedAt, &isLatest)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to update server status: %w", err)
|
||||
}
|
||||
|
||||
// Unmarshal the JSON data
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
// Return the updated ServerResponse
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(currentStatus),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return serverResponse, nil
|
||||
}
|
||||
|
||||
// InTransaction executes a function within a database transaction
|
||||
|
|
@ -479,6 +606,112 @@ func hashServerName(name string) int64 {
|
|||
return int64(hash & 0x7FFFFFFFFFFFFFFF)
|
||||
}
|
||||
|
||||
// GetCurrentLatestVersion retrieves the current latest version of a server by server name
|
||||
func (db *PostgreSQL) GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
executor := db.getExecutor(tx)
|
||||
|
||||
query := `
|
||||
SELECT server_name, version, status, value, published_at, updated_at, is_latest
|
||||
FROM servers
|
||||
WHERE server_name = $1 AND is_latest = true
|
||||
`
|
||||
|
||||
row := executor.QueryRow(ctx, query, serverName)
|
||||
|
||||
var name, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
var jsonValue []byte
|
||||
|
||||
err := row.Scan(&name, &version, &status, &jsonValue, &publishedAt, &updatedAt, &isLatest)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to scan server row: %w", err)
|
||||
}
|
||||
|
||||
// Parse the JSON value to get the server details
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(jsonValue, &serverJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
// Build ServerResponse with separated metadata
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return serverResponse, nil
|
||||
}
|
||||
|
||||
// CountServerVersions counts the number of versions for a server
|
||||
func (db *PostgreSQL) CountServerVersions(ctx context.Context, tx pgx.Tx, serverName string) (int, error) {
|
||||
if ctx.Err() != nil {
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
|
||||
executor := db.getExecutor(tx)
|
||||
|
||||
query := `SELECT COUNT(*) FROM servers WHERE server_name = $1`
|
||||
|
||||
var count int
|
||||
err := executor.QueryRow(ctx, query, serverName).Scan(&count)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("failed to count server versions: %w", err)
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// CheckVersionExists checks if a specific version exists for a server
|
||||
func (db *PostgreSQL) CheckVersionExists(ctx context.Context, tx pgx.Tx, serverName, version string) (bool, error) {
|
||||
if ctx.Err() != nil {
|
||||
return false, ctx.Err()
|
||||
}
|
||||
|
||||
executor := db.getExecutor(tx)
|
||||
|
||||
query := `SELECT EXISTS(SELECT 1 FROM servers WHERE server_name = $1 AND version = $2)`
|
||||
|
||||
var exists bool
|
||||
err := executor.QueryRow(ctx, query, serverName, version).Scan(&exists)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("failed to check version existence: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
// UnmarkAsLatest marks the current latest version of a server as no longer latest
|
||||
func (db *PostgreSQL) UnmarkAsLatest(ctx context.Context, tx pgx.Tx, serverName string) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
executor := db.getExecutor(tx)
|
||||
|
||||
query := `UPDATE servers SET is_latest = false WHERE server_name = $1 AND is_latest = true`
|
||||
|
||||
_, err := executor.Exec(ctx, query, serverName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to unmark latest version: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes the database connection
|
||||
func (db *PostgreSQL) Close() error {
|
||||
db.pool.Close()
|
||||
|
|
|
|||
969
internal/database/postgres_test.go
Normal file
969
internal/database/postgres_test.go
Normal file
|
|
@ -0,0 +1,969 @@
|
|||
package database_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPostgreSQL_CreateServer(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverJSON *apiv0.ServerJSON
|
||||
officialMeta *apiv0.RegistryExtensions
|
||||
expectError bool
|
||||
errorType error
|
||||
}{
|
||||
{
|
||||
name: "successful server creation",
|
||||
serverJSON: &apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "http", URL: "https://api.example.com/mcp"},
|
||||
},
|
||||
},
|
||||
officialMeta: &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "duplicate server version should fail",
|
||||
serverJSON: &apiv0.ServerJSON{
|
||||
Name: "com.example/duplicate-server",
|
||||
Description: "A duplicate test server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
officialMeta: &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
},
|
||||
expectError: true,
|
||||
// Note: Expecting generic database error for constraint violation
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// Create the first server to test duplicates
|
||||
if tt.name == "duplicate server version should fail" {
|
||||
_, err := db.CreateServer(ctx, nil, tt.serverJSON, tt.officialMeta)
|
||||
require.NoError(t, err, "First creation should succeed")
|
||||
}
|
||||
|
||||
result, err := db.CreateServer(ctx, nil, tt.serverJSON, tt.officialMeta)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorType != nil {
|
||||
assert.ErrorIs(t, err, tt.errorType)
|
||||
}
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, tt.serverJSON.Name, result.Server.Name)
|
||||
assert.Equal(t, tt.serverJSON.Version, result.Server.Version)
|
||||
assert.Equal(t, tt.serverJSON.Description, result.Server.Description)
|
||||
assert.NotNil(t, result.Meta.Official)
|
||||
assert.Equal(t, tt.officialMeta.Status, result.Meta.Official.Status)
|
||||
assert.Equal(t, tt.officialMeta.IsLatest, result.Meta.Official.IsLatest)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQL_GetServerByName(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Setup test data
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: "com.example/get-test-server",
|
||||
Description: "A server for get testing",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
// Create the server
|
||||
_, err := db.CreateServer(ctx, nil, serverJSON, officialMeta)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorType error
|
||||
}{
|
||||
{
|
||||
name: "get existing server",
|
||||
serverName: "com.example/get-test-server",
|
||||
},
|
||||
{
|
||||
name: "get non-existent server",
|
||||
serverName: "com.example/non-existent",
|
||||
expectError: true,
|
||||
errorType: database.ErrNotFound,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := db.GetServerByName(ctx, nil, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorType != nil {
|
||||
assert.ErrorIs(t, err, tt.errorType)
|
||||
}
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, tt.serverName, result.Server.Name)
|
||||
assert.NotNil(t, result.Meta.Official)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQL_GetServerByNameAndVersion(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Setup test data with multiple versions
|
||||
serverName := "com.example/version-test-server"
|
||||
versions := []string{"1.0.0", "1.1.0", "2.0.0"}
|
||||
|
||||
for i, version := range versions {
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "A server for version testing",
|
||||
Version: version,
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: i == len(versions)-1, // Only last version is latest
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, nil, serverJSON, officialMeta)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
expectError bool
|
||||
errorType error
|
||||
}{
|
||||
{
|
||||
name: "get existing server version",
|
||||
serverName: serverName,
|
||||
version: "1.1.0",
|
||||
},
|
||||
{
|
||||
name: "get non-existent version",
|
||||
serverName: serverName,
|
||||
version: "3.0.0",
|
||||
expectError: true,
|
||||
errorType: database.ErrNotFound,
|
||||
},
|
||||
{
|
||||
name: "get non-existent server",
|
||||
serverName: "com.example/non-existent",
|
||||
version: "1.0.0",
|
||||
expectError: true,
|
||||
errorType: database.ErrNotFound,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := db.GetServerByNameAndVersion(ctx, nil, tt.serverName, tt.version)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorType != nil {
|
||||
assert.ErrorIs(t, err, tt.errorType)
|
||||
}
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, tt.serverName, result.Server.Name)
|
||||
assert.Equal(t, tt.version, result.Server.Version)
|
||||
assert.NotNil(t, result.Meta.Official)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQL_ListServers(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Setup test data
|
||||
testServers := []struct {
|
||||
name string
|
||||
version string
|
||||
status model.Status
|
||||
remoteURL string
|
||||
isLatest bool
|
||||
publishedAt time.Time
|
||||
}{
|
||||
{
|
||||
name: "com.example/server-a",
|
||||
version: "1.0.0",
|
||||
status: model.StatusActive,
|
||||
remoteURL: "https://api-a.example.com/mcp",
|
||||
isLatest: true,
|
||||
publishedAt: time.Now().Add(-2 * time.Hour),
|
||||
},
|
||||
{
|
||||
name: "com.example/server-b",
|
||||
version: "2.0.0",
|
||||
status: model.StatusActive,
|
||||
remoteURL: "https://api-b.example.com/mcp",
|
||||
isLatest: true,
|
||||
publishedAt: time.Now().Add(-1 * time.Hour),
|
||||
},
|
||||
{
|
||||
name: "com.example/server-c",
|
||||
version: "1.0.0",
|
||||
status: model.StatusDeprecated,
|
||||
remoteURL: "https://api-c.example.com/mcp",
|
||||
isLatest: true,
|
||||
publishedAt: time.Now().Add(-30 * time.Minute),
|
||||
},
|
||||
}
|
||||
|
||||
// Create test servers
|
||||
for _, server := range testServers {
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: server.name,
|
||||
Description: "Test server for listing",
|
||||
Version: server.version,
|
||||
Remotes: []model.Transport{
|
||||
{Type: "http", URL: server.remoteURL},
|
||||
},
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: server.status,
|
||||
PublishedAt: server.publishedAt,
|
||||
UpdatedAt: server.publishedAt,
|
||||
IsLatest: server.isLatest,
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, nil, serverJSON, officialMeta)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
filter *database.ServerFilter
|
||||
cursor string
|
||||
limit int
|
||||
expectedCount int
|
||||
expectedNames []string
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
name: "list all servers",
|
||||
filter: nil,
|
||||
limit: 10,
|
||||
expectedCount: 3,
|
||||
expectedNames: []string{"com.example/server-a", "com.example/server-b", "com.example/server-c"},
|
||||
},
|
||||
{
|
||||
name: "filter by name",
|
||||
filter: &database.ServerFilter{
|
||||
Name: stringPtr("com.example/server-a"),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 1,
|
||||
expectedNames: []string{"com.example/server-a"},
|
||||
},
|
||||
{
|
||||
name: "filter by remote URL",
|
||||
filter: &database.ServerFilter{
|
||||
RemoteURL: stringPtr("https://api-b.example.com/mcp"),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 1,
|
||||
expectedNames: []string{"com.example/server-b"},
|
||||
},
|
||||
{
|
||||
name: "filter by substring name",
|
||||
filter: &database.ServerFilter{
|
||||
SubstringName: stringPtr("server-"),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "filter by version",
|
||||
filter: &database.ServerFilter{
|
||||
Version: stringPtr("1.0.0"),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 2,
|
||||
},
|
||||
{
|
||||
name: "filter by isLatest",
|
||||
filter: &database.ServerFilter{
|
||||
IsLatest: boolPtr(true),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "filter by updatedSince",
|
||||
filter: &database.ServerFilter{
|
||||
UpdatedSince: timePtr(time.Now().Add(-45 * time.Minute)),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 1, // Only server-c was updated in the last 45 minutes
|
||||
},
|
||||
{
|
||||
name: "test pagination with limit",
|
||||
filter: nil,
|
||||
limit: 2,
|
||||
expectedCount: 2,
|
||||
},
|
||||
{
|
||||
name: "test cursor pagination",
|
||||
filter: nil,
|
||||
cursor: "com.example/server-a",
|
||||
limit: 10,
|
||||
// Should return servers after 'server-a' alphabetically
|
||||
expectedCount: 2,
|
||||
expectedNames: []string{"com.example/server-b", "com.example/server-c"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
results, nextCursor, err := db.ListServers(ctx, nil, tt.filter, tt.cursor, tt.limit)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, results, tt.expectedCount)
|
||||
|
||||
if len(tt.expectedNames) > 0 {
|
||||
actualNames := make([]string, len(results))
|
||||
for i, result := range results {
|
||||
actualNames[i] = result.Server.Name
|
||||
}
|
||||
assert.Subset(t, tt.expectedNames, actualNames)
|
||||
}
|
||||
|
||||
// Test cursor behavior
|
||||
if tt.limit < len(testServers) && len(results) == tt.limit {
|
||||
assert.NotEmpty(t, nextCursor, "Should return next cursor when results are limited")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQL_UpdateServer(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Setup test data
|
||||
serverName := "com.example/update-test-server"
|
||||
version := "1.0.0"
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Original description",
|
||||
Version: version,
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, nil, serverJSON, officialMeta)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
updatedServer *apiv0.ServerJSON
|
||||
expectError bool
|
||||
errorType error
|
||||
}{
|
||||
{
|
||||
name: "successful server update",
|
||||
serverName: serverName,
|
||||
version: version,
|
||||
updatedServer: &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Updated description",
|
||||
Version: version,
|
||||
Remotes: []model.Transport{
|
||||
{Type: "http", URL: "https://updated.example.com/mcp"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update non-existent server",
|
||||
serverName: "com.example/non-existent",
|
||||
version: "1.0.0",
|
||||
updatedServer: &apiv0.ServerJSON{
|
||||
Name: "com.example/non-existent",
|
||||
Description: "Should fail",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectError: true,
|
||||
errorType: database.ErrNotFound,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := db.UpdateServer(ctx, nil, tt.serverName, tt.version, tt.updatedServer)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorType != nil {
|
||||
assert.ErrorIs(t, err, tt.errorType)
|
||||
}
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, tt.updatedServer.Description, result.Server.Description)
|
||||
assert.NotNil(t, result.Meta.Official)
|
||||
assert.NotZero(t, result.Meta.Official.UpdatedAt)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQL_SetServerStatus(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Setup test data
|
||||
serverName := "com.example/status-test-server"
|
||||
version := "1.0.0"
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "A server for status testing",
|
||||
Version: version,
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, nil, serverJSON, officialMeta)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
newStatus string
|
||||
expectError bool
|
||||
errorType error
|
||||
}{
|
||||
{
|
||||
name: "active to deprecated",
|
||||
serverName: serverName,
|
||||
version: version,
|
||||
newStatus: string(model.StatusDeprecated),
|
||||
},
|
||||
{
|
||||
name: "invalid status",
|
||||
serverName: serverName,
|
||||
version: version,
|
||||
newStatus: "invalid_status",
|
||||
expectError: true,
|
||||
},
|
||||
{
|
||||
name: "non-existent server",
|
||||
serverName: "com.example/non-existent",
|
||||
version: "1.0.1",
|
||||
newStatus: string(model.StatusDeprecated),
|
||||
expectError: true,
|
||||
errorType: database.ErrNotFound,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := db.SetServerStatus(ctx, nil, tt.serverName, tt.version, tt.newStatus)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorType != nil {
|
||||
assert.ErrorIs(t, err, tt.errorType)
|
||||
}
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, model.Status(tt.newStatus), result.Meta.Official.Status)
|
||||
assert.NotZero(t, result.Meta.Official.UpdatedAt)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQL_TransactionHandling(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("successful transaction", func(t *testing.T) {
|
||||
err := db.InTransaction(ctx, func(ctx context.Context, tx pgx.Tx) error {
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: "com.example/transaction-success",
|
||||
Description: "Transaction test server",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, tx, serverJSON, officialMeta)
|
||||
return err
|
||||
})
|
||||
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify server was created
|
||||
result, err := db.GetServerByName(ctx, nil, "com.example/transaction-success")
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
})
|
||||
|
||||
t.Run("failed transaction rollback", func(t *testing.T) {
|
||||
err := db.InTransaction(ctx, func(ctx context.Context, tx pgx.Tx) error {
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: "com.example/transaction-rollback",
|
||||
Description: "Transaction rollback test server",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, tx, serverJSON, officialMeta)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Force an error to trigger rollback
|
||||
return assert.AnError
|
||||
})
|
||||
|
||||
assert.Error(t, err)
|
||||
assert.Equal(t, assert.AnError, err)
|
||||
|
||||
// Verify server was NOT created due to rollback
|
||||
result, err := db.GetServerByName(ctx, nil, "com.example/transaction-rollback")
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, database.ErrNotFound)
|
||||
assert.Nil(t, result)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPostgreSQL_ConcurrencyAndLocking(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
serverName := "com.example/concurrent-server"
|
||||
|
||||
// Test advisory locking prevents concurrent publishes
|
||||
t.Run("advisory locking prevents race conditions", func(t *testing.T) {
|
||||
published := make(chan bool, 2)
|
||||
errors := make(chan error, 2)
|
||||
|
||||
// Launch two concurrent publish operations
|
||||
for i := 0; i < 2; i++ {
|
||||
go func(version string) {
|
||||
err := db.InTransaction(ctx, func(ctx context.Context, tx pgx.Tx) error {
|
||||
// Acquire lock
|
||||
if err := db.AcquirePublishLock(ctx, tx, serverName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Simulate some processing time
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Concurrent test server",
|
||||
Version: version,
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, tx, serverJSON, officialMeta)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
published <- true
|
||||
return nil
|
||||
})
|
||||
errors <- err
|
||||
}(time.Now().Format("20060102150405.000000"))
|
||||
}
|
||||
|
||||
// Wait for both goroutines to complete
|
||||
err1 := <-errors
|
||||
err2 := <-errors
|
||||
|
||||
// One should succeed, one should wait (or fail if timeout)
|
||||
successCount := 0
|
||||
if err1 == nil {
|
||||
successCount++
|
||||
}
|
||||
if err2 == nil {
|
||||
successCount++
|
||||
}
|
||||
|
||||
// At least one should succeed (both can succeed if advisory lock works properly)
|
||||
assert.GreaterOrEqual(t, successCount, 1, "At least one concurrent operation should succeed")
|
||||
|
||||
close(published)
|
||||
close(errors)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPostgreSQL_HelperMethods(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
serverName := "com.example/helper-test-server"
|
||||
|
||||
// Setup test data with multiple versions
|
||||
versions := []string{"1.0.0", "1.1.0", "2.0.0"}
|
||||
for _, version := range versions {
|
||||
serverJSON := &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Helper methods test server",
|
||||
Version: version,
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: version == "2.0.0",
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, nil, serverJSON, officialMeta)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
t.Run("CountServerVersions", func(t *testing.T) {
|
||||
count, err := db.CountServerVersions(ctx, nil, serverName)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 3, count)
|
||||
|
||||
// Test non-existent server
|
||||
count, err = db.CountServerVersions(ctx, nil, "com.example/non-existent")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 0, count)
|
||||
})
|
||||
|
||||
t.Run("CheckVersionExists", func(t *testing.T) {
|
||||
exists, err := db.CheckVersionExists(ctx, nil, serverName, "1.1.0")
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, exists)
|
||||
|
||||
exists, err = db.CheckVersionExists(ctx, nil, serverName, "3.0.0")
|
||||
assert.NoError(t, err)
|
||||
assert.False(t, exists)
|
||||
})
|
||||
|
||||
t.Run("GetCurrentLatestVersion", func(t *testing.T) {
|
||||
latest, err := db.GetCurrentLatestVersion(ctx, nil, serverName)
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, latest)
|
||||
assert.Equal(t, "2.0.0", latest.Server.Version)
|
||||
assert.True(t, latest.Meta.Official.IsLatest)
|
||||
})
|
||||
|
||||
t.Run("GetAllVersionsByServerName", func(t *testing.T) {
|
||||
allVersions, err := db.GetAllVersionsByServerName(ctx, nil, serverName)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, allVersions, 3)
|
||||
|
||||
// Check versions are present
|
||||
versionSet := make(map[string]bool)
|
||||
for _, server := range allVersions {
|
||||
versionSet[server.Server.Version] = true
|
||||
}
|
||||
for _, expectedVersion := range versions {
|
||||
assert.True(t, versionSet[expectedVersion], "Version %s should be present", expectedVersion)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("UnmarkAsLatest", func(t *testing.T) {
|
||||
err := db.UnmarkAsLatest(ctx, nil, serverName)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Verify no version is marked as latest
|
||||
latest, err := db.GetCurrentLatestVersion(ctx, nil, serverName)
|
||||
assert.Error(t, err)
|
||||
assert.ErrorIs(t, err, database.ErrNotFound)
|
||||
assert.Nil(t, latest)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPostgreSQL_EdgeCases(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("input validation", func(t *testing.T) {
|
||||
// Test nil inputs
|
||||
_, err := db.CreateServer(ctx, nil, nil, nil)
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "serverJSON and officialMeta are required")
|
||||
|
||||
// Test empty required fields
|
||||
_, err = db.CreateServer(ctx, nil, &apiv0.ServerJSON{}, &apiv0.RegistryExtensions{})
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "server name and version are required")
|
||||
})
|
||||
|
||||
t.Run("database constraints", func(t *testing.T) {
|
||||
// Test server name format constraint (should be caught by database constraint)
|
||||
invalidServer := &apiv0.ServerJSON{
|
||||
Name: "invalid-name-format", // Missing namespace/name format
|
||||
Description: "Invalid server",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
}
|
||||
|
||||
_, err := db.CreateServer(ctx, nil, invalidServer, officialMeta)
|
||||
assert.Error(t, err, "Should fail due to server name format constraint")
|
||||
})
|
||||
|
||||
t.Run("pagination edge cases", func(t *testing.T) {
|
||||
// Test pagination with no results
|
||||
results, cursor, err := db.ListServers(ctx, nil, &database.ServerFilter{
|
||||
Name: stringPtr("com.example/non-existent-server"),
|
||||
}, "", 10)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, results)
|
||||
assert.Empty(t, cursor)
|
||||
|
||||
// Test pagination with limit 0 (should use default)
|
||||
_, _, err = db.ListServers(ctx, nil, nil, "", 0)
|
||||
assert.NoError(t, err)
|
||||
// Should still work with default limit
|
||||
})
|
||||
|
||||
t.Run("complex filtering", func(t *testing.T) {
|
||||
// Setup test data
|
||||
serverName := "com.example/complex-filter-server"
|
||||
testTime := time.Now().Add(-1 * time.Hour)
|
||||
|
||||
_, err := db.CreateServer(ctx, nil, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Complex filter test server",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: "https://complex.example.com/mcp"},
|
||||
},
|
||||
}, &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: testTime,
|
||||
UpdatedAt: testTime,
|
||||
IsLatest: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Test multiple filters combined
|
||||
filter := &database.ServerFilter{
|
||||
SubstringName: stringPtr("complex"),
|
||||
UpdatedSince: timePtr(testTime.Add(-30 * time.Minute)),
|
||||
IsLatest: boolPtr(true),
|
||||
Version: stringPtr("1.0.0"),
|
||||
}
|
||||
|
||||
results, _, err := db.ListServers(ctx, nil, filter, "", 10)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, results, 1)
|
||||
assert.Equal(t, serverName, results[0].Server.Name)
|
||||
})
|
||||
|
||||
t.Run("status transitions", func(t *testing.T) {
|
||||
serverName := "com.example/status-transition-server"
|
||||
version := "1.0.2"
|
||||
|
||||
// Create server
|
||||
_, err := db.CreateServer(ctx, nil, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Status transition test",
|
||||
Version: version,
|
||||
}, &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Test all valid status transitions
|
||||
statuses := []string{
|
||||
string(model.StatusDeprecated),
|
||||
string(model.StatusDeleted),
|
||||
string(model.StatusActive), // Can transition back
|
||||
}
|
||||
|
||||
for _, status := range statuses {
|
||||
result, err := db.SetServerStatus(ctx, nil, serverName, version, status)
|
||||
assert.NoError(t, err, "Should allow transition to %s", status)
|
||||
assert.Equal(t, model.Status(status), result.Meta.Official.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPostgreSQL_PerformanceScenarios(t *testing.T) {
|
||||
db := database.NewTestDB(t)
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("many versions management", func(t *testing.T) {
|
||||
serverName := "com.example/many-versions-server"
|
||||
|
||||
// Create many versions (but stay under the limit)
|
||||
versionCount := 50
|
||||
for i := 0; i < versionCount; i++ {
|
||||
_, err := db.CreateServer(ctx, nil, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: fmt.Sprintf("Version %d", i),
|
||||
Version: fmt.Sprintf("1.0.%d", i),
|
||||
}, &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: i == versionCount-1, // Only last one is latest
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Test counting versions
|
||||
count, err := db.CountServerVersions(ctx, nil, serverName)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, versionCount, count)
|
||||
|
||||
// Test getting all versions
|
||||
allVersions, err := db.GetAllVersionsByServerName(ctx, nil, serverName)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, allVersions, versionCount)
|
||||
|
||||
// Test only one is marked as latest
|
||||
latestCount := 0
|
||||
for _, version := range allVersions {
|
||||
if version.Meta.Official.IsLatest {
|
||||
latestCount++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, latestCount)
|
||||
})
|
||||
|
||||
t.Run("large result pagination", func(t *testing.T) {
|
||||
// Create multiple servers for pagination testing
|
||||
serverCount := 25
|
||||
for i := 0; i < serverCount; i++ {
|
||||
_, err := db.CreateServer(ctx, nil, &apiv0.ServerJSON{
|
||||
Name: fmt.Sprintf("com.example/pagination-server-%02d", i),
|
||||
Description: "Pagination test server",
|
||||
Version: "1.0.0",
|
||||
}, &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive,
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Test paginated retrieval
|
||||
allResults := []*apiv0.ServerResponse{}
|
||||
cursor := ""
|
||||
pageSize := 10
|
||||
|
||||
for {
|
||||
results, nextCursor, err := db.ListServers(ctx, nil, nil, cursor, pageSize)
|
||||
assert.NoError(t, err)
|
||||
allResults = append(allResults, results...)
|
||||
|
||||
if nextCursor == "" || len(results) < pageSize {
|
||||
break
|
||||
}
|
||||
cursor = nextCursor
|
||||
}
|
||||
|
||||
// Should have retrieved all servers including the ones we just created
|
||||
assert.GreaterOrEqual(t, len(allResults), serverCount)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper functions for creating pointers to basic types
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
func boolPtr(b bool) *bool {
|
||||
return &b
|
||||
}
|
||||
|
||||
func timePtr(t time.Time) *time.Time {
|
||||
return &t
|
||||
}
|
||||
|
|
@ -10,24 +10,24 @@ import (
|
|||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
"github.com/modelcontextprotocol/registry/internal/validators"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
)
|
||||
|
||||
// Service handles importing seed data into the registry
|
||||
type Service struct {
|
||||
db database.Database
|
||||
registry service.RegistryService
|
||||
}
|
||||
|
||||
// NewService creates a new importer service
|
||||
func NewService(db database.Database) *Service {
|
||||
return &Service{db: db}
|
||||
func NewService(registry service.RegistryService) *Service {
|
||||
return &Service{registry: registry}
|
||||
}
|
||||
|
||||
// ImportFromPath imports seed data from various sources:
|
||||
// 1. Local file paths (*.json files) - expects extension wrapper format
|
||||
// 2. Direct HTTP URLs to seed.json files - expects extension wrapper format
|
||||
// 1. Local file paths (*.json files) - expects ServerJSON array format
|
||||
// 2. Direct HTTP URLs to seed.json files - expects ServerJSON array format
|
||||
// 3. Registry root URLs (automatically appends /v0/servers and paginates)
|
||||
func (s *Service) ImportFromPath(ctx context.Context, path string) error {
|
||||
servers, err := readSeedFile(ctx, path)
|
||||
|
|
@ -35,14 +35,29 @@ func (s *Service) ImportFromPath(ctx context.Context, path string) error {
|
|||
return fmt.Errorf("failed to read seed data: %w", err)
|
||||
}
|
||||
|
||||
// Import each server using CreateServer
|
||||
// Import each server using registry service CreateServer
|
||||
var successfullyCreated []string
|
||||
var failedCreations []string
|
||||
|
||||
for _, server := range servers {
|
||||
_, err := s.db.CreateServer(ctx, nil, server)
|
||||
_, err := s.registry.CreateServer(ctx, server)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to import server %s: %w", server.Name, err)
|
||||
failedCreations = append(failedCreations, fmt.Sprintf("%s: %v", server.Name, err))
|
||||
log.Printf("Failed to create server %s: %v", server.Name, err)
|
||||
} else {
|
||||
successfullyCreated = append(successfullyCreated, server.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Report import results after actual creation attempts
|
||||
if len(failedCreations) > 0 {
|
||||
log.Printf("Import completed with errors: %d servers created successfully, %d servers failed",
|
||||
len(successfullyCreated), len(failedCreations))
|
||||
log.Printf("Failed servers: %v", failedCreations)
|
||||
return fmt.Errorf("failed to import %d servers", len(failedCreations))
|
||||
}
|
||||
|
||||
log.Printf("Import completed successfully: all %d servers created", len(successfullyCreated))
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -69,10 +84,10 @@ func readSeedFile(ctx context.Context, path string) ([]*apiv0.ServerJSON, error)
|
|||
return nil, fmt.Errorf("failed to read seed data from %s: %w", path, err)
|
||||
}
|
||||
|
||||
// Parse extension wrapper format (only supported format)
|
||||
// Parse ServerJSON array format
|
||||
var serverResponses []apiv0.ServerJSON
|
||||
if err := json.Unmarshal(data, &serverResponses); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse seed data as extension wrapper format: %w", err)
|
||||
return nil, fmt.Errorf("failed to parse seed data as ServerJSON array format: %w", err)
|
||||
}
|
||||
|
||||
if len(serverResponses) == 0 {
|
||||
|
|
@ -93,20 +108,19 @@ func readSeedFile(ctx context.Context, path string) ([]*apiv0.ServerJSON, error)
|
|||
continue
|
||||
}
|
||||
|
||||
// Convert valid ServerJSON to ServerRecord
|
||||
record := convertServerResponseToRecord(response)
|
||||
validRecords = append(validRecords, record)
|
||||
// Add valid ServerJSON to records
|
||||
validRecords = append(validRecords, &response)
|
||||
}
|
||||
|
||||
// Print summary of validation results
|
||||
if len(invalidServers) > 0 {
|
||||
log.Printf("Import summary: %d valid servers imported, %d invalid servers skipped", len(validRecords), len(invalidServers))
|
||||
log.Printf("Validation summary: %d servers passed validation, %d invalid servers skipped", len(validRecords), len(invalidServers))
|
||||
log.Printf("Invalid servers: %v", invalidServers)
|
||||
for _, failure := range validationFailures {
|
||||
log.Printf(" - %s", failure)
|
||||
}
|
||||
} else {
|
||||
log.Printf("Import summary: All %d servers imported successfully", len(validRecords))
|
||||
log.Printf("Validation summary: All %d servers passed validation", len(validRecords))
|
||||
}
|
||||
|
||||
return validRecords, nil
|
||||
|
|
@ -151,9 +165,9 @@ func fetchFromRegistryAPI(ctx context.Context, baseURL string) ([]*apiv0.ServerJ
|
|||
}
|
||||
|
||||
var response struct {
|
||||
Servers []apiv0.ServerJSON `json:"servers"`
|
||||
Servers []apiv0.ServerResponse `json:"servers"`
|
||||
Metadata *struct {
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
NextCursor string `json:"nextCursor,omitempty"`
|
||||
} `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
|
|
@ -161,10 +175,9 @@ func fetchFromRegistryAPI(ctx context.Context, baseURL string) ([]*apiv0.ServerJ
|
|||
return nil, fmt.Errorf("failed to parse registry API response: %w", err)
|
||||
}
|
||||
|
||||
// Convert and add servers
|
||||
// Extract ServerJSON from each ServerResponse
|
||||
for _, serverResponse := range response.Servers {
|
||||
record := convertServerResponseToRecord(serverResponse)
|
||||
allRecords = append(allRecords, record)
|
||||
allRecords = append(allRecords, &serverResponse.Server)
|
||||
}
|
||||
|
||||
// Check if there's a next page
|
||||
|
|
@ -177,8 +190,3 @@ func fetchFromRegistryAPI(ctx context.Context, baseURL string) ([]*apiv0.ServerJ
|
|||
return allRecords, nil
|
||||
}
|
||||
|
||||
func convertServerResponseToRecord(response apiv0.ServerJSON) *apiv0.ServerJSON {
|
||||
// The response is already in the correct flattened format
|
||||
// Just return a pointer to it
|
||||
return &response
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,10 +7,11 @@ import (
|
|||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/importer"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
|
@ -20,7 +21,7 @@ import (
|
|||
func TestImportService_LocalFile(t *testing.T) {
|
||||
// Create a temporary seed file
|
||||
tempFile := "/tmp/test_import_seed.json"
|
||||
seedData := []apiv0.ServerJSON{
|
||||
seedData := []*apiv0.ServerJSON{
|
||||
{
|
||||
Name: "io.github.test/test-server-1",
|
||||
Description: "Test server 1",
|
||||
|
|
@ -30,15 +31,6 @@ func TestImportService_LocalFile(t *testing.T) {
|
|||
ID: "123",
|
||||
},
|
||||
Version: "1.0.0",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
ServerID: "server-id-1",
|
||||
VersionID: "test-id-1",
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -49,149 +41,201 @@ func TestImportService_LocalFile(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
defer os.Remove(tempFile)
|
||||
|
||||
// Create registry service
|
||||
testDB := database.NewTestDB(t)
|
||||
registryService := service.NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Create importer service and test import
|
||||
service := importer.NewService(testDB)
|
||||
err = service.ImportFromPath(context.Background(), tempFile)
|
||||
importerService := importer.NewService(registryService)
|
||||
err = importerService.ImportFromPath(context.Background(), tempFile)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify the server was imported
|
||||
servers, _, err := testDB.List(context.Background(), nil, nil, "", 10)
|
||||
// Verify the server was imported using registry service
|
||||
servers, _, err := registryService.ListServers(context.Background(), nil, "", 10)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, servers, 1)
|
||||
assert.Equal(t, "io.github.test/test-server-1", servers[0].Name)
|
||||
assert.Equal(t, "io.github.test/test-server-1", servers[0].Server.Name)
|
||||
assert.Equal(t, "1.0.0", servers[0].Server.Version)
|
||||
assert.Equal(t, "Test server 1", servers[0].Server.Description)
|
||||
assert.NotNil(t, servers[0].Meta.Official)
|
||||
assert.Equal(t, model.StatusActive, servers[0].Meta.Official.Status)
|
||||
}
|
||||
|
||||
func TestImportService_HTTPFile(t *testing.T) {
|
||||
// Create a test HTTP server
|
||||
seedData := []apiv0.ServerJSON{
|
||||
seedData := []*apiv0.ServerJSON{
|
||||
{
|
||||
Name: "io.github.test/http-test-server",
|
||||
Description: "HTTP test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/test/repo1",
|
||||
Source: "github",
|
||||
ID: "123",
|
||||
},
|
||||
Version: "2.0.0",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
ServerID: "server-id-test",
|
||||
VersionID: "test-id-2",
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(seedData)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
testDB := database.NewTestDB(t)
|
||||
|
||||
// Create importer service and test import
|
||||
service := importer.NewService(testDB)
|
||||
err := service.ImportFromPath(context.Background(), server.URL+"/seed.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify the server was imported
|
||||
servers, _, err := testDB.List(context.Background(), nil, nil, "", 10)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, servers, 1)
|
||||
assert.Equal(t, "io.github.test/http-test-server", servers[0].Name)
|
||||
}
|
||||
|
||||
func TestImportService_RegistryAPI(t *testing.T) {
|
||||
// Create test data
|
||||
testServers := []apiv0.ServerJSON{
|
||||
{
|
||||
Name: "io.github.test/api-server-1",
|
||||
Description: "API server 1",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/test/repo1",
|
||||
Source: "github",
|
||||
ID: "123",
|
||||
},
|
||||
Version: "1.0.0",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
ServerID: "server-id-test-1",
|
||||
VersionID: "api-test-id-1",
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "io.github.test/api-server-2",
|
||||
Description: "API server 2",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/test/repo2",
|
||||
URL: "https://github.com/test/http-repo",
|
||||
Source: "github",
|
||||
ID: "456",
|
||||
},
|
||||
Version: "2.0.0",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
ServerID: "server-id-test-2",
|
||||
VersionID: "api-test-id-2",
|
||||
PublishedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
IsLatest: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create test server that responds with paginated results
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
jsonData, err := json.Marshal(seedData)
|
||||
require.NoError(t, err)
|
||||
|
||||
var response struct {
|
||||
Servers []apiv0.ServerJSON `json:"servers"`
|
||||
Metadata *struct {
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
} `json:"metadata,omitempty"`
|
||||
// Create test HTTP server
|
||||
httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write(jsonData)
|
||||
}))
|
||||
defer httpServer.Close()
|
||||
|
||||
// Create registry service
|
||||
testDB := database.NewTestDB(t)
|
||||
registryService := service.NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Create importer service and test import
|
||||
importerService := importer.NewService(registryService)
|
||||
err = importerService.ImportFromPath(context.Background(), httpServer.URL+"/seed.json")
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify the server was imported
|
||||
servers, _, err := registryService.ListServers(context.Background(), nil, "", 10)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, servers, 1)
|
||||
assert.Equal(t, "io.github.test/http-test-server", servers[0].Server.Name)
|
||||
assert.Equal(t, "2.0.0", servers[0].Server.Version)
|
||||
assert.Equal(t, "HTTP test server", servers[0].Server.Description)
|
||||
assert.NotNil(t, servers[0].Meta.Official)
|
||||
}
|
||||
|
||||
func TestImportService_RegistryPagination(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// Create registry service with test data
|
||||
testDB := database.NewTestDB(t)
|
||||
registryService := service.NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Setup source registry with test data
|
||||
sourceServers := []*apiv0.ServerJSON{
|
||||
{
|
||||
Name: "com.source/server-1",
|
||||
Description: "Source server 1",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
{
|
||||
Name: "com.source/server-2",
|
||||
Description: "Source server 2",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
}
|
||||
|
||||
for _, server := range sourceServers {
|
||||
_, err := registryService.CreateServer(ctx, server)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Create test HTTP server that serves the registry API
|
||||
httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
servers, _, _ := registryService.ListServers(ctx, nil, "", 10)
|
||||
|
||||
// Convert to response format
|
||||
serverValues := make([]apiv0.ServerResponse, len(servers))
|
||||
for i, server := range servers {
|
||||
serverValues[i] = *server
|
||||
}
|
||||
|
||||
switch cursor {
|
||||
case "":
|
||||
// First page
|
||||
response.Servers = []apiv0.ServerJSON{testServers[0]}
|
||||
response.Metadata = &struct {
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
}{NextCursor: "page2"}
|
||||
case "page2":
|
||||
// Second page
|
||||
response.Servers = []apiv0.ServerJSON{testServers[1]}
|
||||
// No next cursor means end of results
|
||||
response := apiv0.ServerListResponse{
|
||||
Servers: serverValues,
|
||||
Metadata: apiv0.Metadata{
|
||||
Count: len(servers),
|
||||
},
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(response)
|
||||
}))
|
||||
defer server.Close()
|
||||
defer httpServer.Close()
|
||||
|
||||
testDB := database.NewTestDB(t)
|
||||
// Create target registry for import
|
||||
targetDB := database.NewTestDB(t)
|
||||
targetRegistryService := service.NewRegistryService(targetDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Create importer service and test import
|
||||
service := importer.NewService(testDB)
|
||||
err := service.ImportFromPath(context.Background(), server.URL+"/v0/servers")
|
||||
// Create importer service and test registry import
|
||||
importerService := importer.NewService(targetRegistryService)
|
||||
err := importerService.ImportFromPath(context.Background(), httpServer.URL+"/v0/servers")
|
||||
require.NoError(t, err)
|
||||
|
||||
// Verify both servers were imported
|
||||
servers, _, err := testDB.List(context.Background(), nil, nil, "", 10)
|
||||
// Verify servers were imported
|
||||
importedServers, _, err := targetRegistryService.ListServers(context.Background(), nil, "", 10)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, servers, 2)
|
||||
assert.Len(t, importedServers, 2)
|
||||
|
||||
names := []string{servers[0].Name, servers[1].Name}
|
||||
assert.Contains(t, names, "io.github.test/api-server-1")
|
||||
assert.Contains(t, names, "io.github.test/api-server-2")
|
||||
// Verify server details
|
||||
serverNames := make([]string, len(importedServers))
|
||||
for i, server := range importedServers {
|
||||
serverNames[i] = server.Server.Name
|
||||
}
|
||||
assert.Contains(t, serverNames, "com.source/server-1")
|
||||
assert.Contains(t, serverNames, "com.source/server-2")
|
||||
}
|
||||
|
||||
func TestImportService_ErrorHandling(t *testing.T) {
|
||||
// Create registry service
|
||||
testDB := database.NewTestDB(t)
|
||||
registryService := service.NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
importerService := importer.NewService(registryService)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
expectError bool
|
||||
errorMsg string
|
||||
}{
|
||||
{
|
||||
name: "non-existent local file",
|
||||
path: "/tmp/non-existent-file.json",
|
||||
expectError: true,
|
||||
errorMsg: "failed to read seed data",
|
||||
},
|
||||
{
|
||||
name: "invalid JSON file",
|
||||
path: "/tmp/invalid.json",
|
||||
expectError: true,
|
||||
errorMsg: "failed to read seed data",
|
||||
},
|
||||
{
|
||||
name: "non-existent HTTP URL",
|
||||
path: "http://non-existent-domain-12345.com/seed.json",
|
||||
expectError: true,
|
||||
errorMsg: "failed to read seed data",
|
||||
},
|
||||
}
|
||||
|
||||
// Create invalid JSON file for testing
|
||||
invalidJSON := []byte("{invalid json}")
|
||||
tempFile, err := os.CreateTemp("", "invalid-*.json")
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(tempFile.Name())
|
||||
err = os.WriteFile(tempFile.Name(), invalidJSON, 0600)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Update test case to use temp file
|
||||
for i := range tests {
|
||||
if tests[i].path == "/tmp/invalid.json" {
|
||||
tests[i].path = tempFile.Name()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := importerService.ImportFromPath(context.Background(), tt.path)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorMsg != "" {
|
||||
assert.Contains(t, err.Error(), tt.errorMsg)
|
||||
}
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,12 +6,12 @@ import (
|
|||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/validators"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
const maxServerVersionsPerServer = 10000
|
||||
|
|
@ -30,219 +30,136 @@ func NewRegistryService(db database.Database, cfg *config.Config) RegistryServic
|
|||
}
|
||||
}
|
||||
|
||||
// List returns registry entries with cursor-based pagination and optional filtering
|
||||
func (s *registryServiceImpl) List(filter *database.ServerFilter, cursor string, limit int) ([]apiv0.ServerJSON, string, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// ListServers returns registry entries with cursor-based pagination and optional filtering
|
||||
func (s *registryServiceImpl) ListServers(ctx context.Context, filter *database.ServerFilter, cursor string, limit int) ([]*apiv0.ServerResponse, string, error) {
|
||||
// If limit is not set or negative, use a default limit
|
||||
if limit <= 0 {
|
||||
limit = 30
|
||||
}
|
||||
|
||||
// Use the database's ListServers method with pagination and filtering
|
||||
serverRecords, nextCursor, err := s.db.List(ctx, nil, filter, cursor, limit)
|
||||
serverRecords, nextCursor, err := s.db.ListServers(ctx, nil, filter, cursor, limit)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// Return ServerJSONs directly
|
||||
result := make([]apiv0.ServerJSON, len(serverRecords))
|
||||
for i, record := range serverRecords {
|
||||
result[i] = *record
|
||||
}
|
||||
|
||||
return result, nextCursor, nil
|
||||
return serverRecords, nextCursor, nil
|
||||
}
|
||||
|
||||
// GetByVersionID retrieves a specific server by its registry metadata version ID
|
||||
func (s *registryServiceImpl) GetByVersionID(versionID string) (*apiv0.ServerJSON, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
serverRecord, err := s.db.GetByVersionID(ctx, nil, versionID)
|
||||
// GetServerByName retrieves the latest version of a server by its server name
|
||||
func (s *registryServiceImpl) GetServerByName(ctx context.Context, serverName string) (*apiv0.ServerResponse, error) {
|
||||
serverRecord, err := s.db.GetServerByName(ctx, nil, serverName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Return the server record directly
|
||||
return serverRecord, nil
|
||||
}
|
||||
|
||||
// GetByServerID retrieves the latest version of a server by its server ID
|
||||
func (s *registryServiceImpl) GetByServerID(serverID string) (*apiv0.ServerJSON, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
serverRecord, err := s.db.GetByServerID(ctx, nil, serverID)
|
||||
// GetServerByNameAndVersion retrieves a specific version of a server by server name and version
|
||||
func (s *registryServiceImpl) GetServerByNameAndVersion(ctx context.Context, serverName string, version string) (*apiv0.ServerResponse, error) {
|
||||
serverRecord, err := s.db.GetServerByNameAndVersion(ctx, nil, serverName, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Return the server record directly
|
||||
return serverRecord, nil
|
||||
}
|
||||
|
||||
// GetByServerIDAndVersion retrieves a specific version of a server by server ID and version
|
||||
func (s *registryServiceImpl) GetByServerIDAndVersion(serverID string, version string) (*apiv0.ServerJSON, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
serverRecord, err := s.db.GetByServerIDAndVersion(ctx, nil, serverID, version)
|
||||
// GetAllVersionsByServerName retrieves all versions of a server by server name
|
||||
func (s *registryServiceImpl) GetAllVersionsByServerName(ctx context.Context, serverName string) ([]*apiv0.ServerResponse, error) {
|
||||
serverRecords, err := s.db.GetAllVersionsByServerName(ctx, nil, serverName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Return the server record directly
|
||||
return serverRecord, nil
|
||||
return serverRecords, nil
|
||||
}
|
||||
|
||||
// GetAllVersionsByServerID retrieves all versions of a server by server ID
|
||||
func (s *registryServiceImpl) GetAllVersionsByServerID(serverID string) ([]apiv0.ServerJSON, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
serverRecords, err := s.db.GetAllVersionsByServerID(ctx, nil, serverID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Return ServerJSONs directly
|
||||
result := make([]apiv0.ServerJSON, len(serverRecords))
|
||||
for i, record := range serverRecords {
|
||||
result[i] = *record
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Publish publishes a server with flattened _meta extensions
|
||||
func (s *registryServiceImpl) Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Validate the request
|
||||
if err := validators.ValidatePublishRequest(req, s.cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result, err := database.InTransactionT(ctx, s.db, func(txCtx context.Context, tx pgx.Tx) (*apiv0.ServerJSON, error) {
|
||||
publishTime := time.Now()
|
||||
serverJSON := req
|
||||
|
||||
// Acquire advisory lock to prevent concurrent publishes of the same server
|
||||
if err := s.db.AcquirePublishLock(txCtx, tx, serverJSON.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check for duplicate remote URLs
|
||||
if err := s.validateNoDuplicateRemoteURLs(txCtx, tx, serverJSON); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
filter := &database.ServerFilter{Name: &serverJSON.Name}
|
||||
existingServerVersions, _, err := s.db.List(txCtx, tx, filter, "", maxServerVersionsPerServer)
|
||||
if err != nil && !errors.Is(err, database.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check we haven't exceeded the maximum versions allowed for a server
|
||||
if len(existingServerVersions) >= maxServerVersionsPerServer {
|
||||
return nil, database.ErrMaxServersReached
|
||||
}
|
||||
|
||||
// Check this isn't a duplicate version
|
||||
for _, server := range existingServerVersions {
|
||||
existingVersion := server.Version
|
||||
if existingVersion == serverJSON.Version {
|
||||
return nil, database.ErrInvalidVersion
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if this version should be marked as latest
|
||||
existingLatest := s.getCurrentLatestVersion(existingServerVersions)
|
||||
isNewLatest := true
|
||||
if existingLatest != nil {
|
||||
var existingPublishedAt time.Time
|
||||
if existingLatest.Meta != nil && existingLatest.Meta.Official != nil {
|
||||
existingPublishedAt = existingLatest.Meta.Official.PublishedAt
|
||||
}
|
||||
isNewLatest = CompareVersions(
|
||||
serverJSON.Version,
|
||||
existingLatest.Version,
|
||||
publishTime,
|
||||
existingPublishedAt,
|
||||
) > 0
|
||||
}
|
||||
|
||||
// Unmark old latest version if needed
|
||||
if isNewLatest && existingLatest != nil {
|
||||
if existingLatest.Meta != nil && existingLatest.Meta.Official != nil {
|
||||
existingLatest.Meta.Official.IsLatest = false
|
||||
if _, err := s.db.UpdateServer(txCtx, tx, existingLatest.Meta.Official.VersionID, existingLatest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Create complete server with metadata
|
||||
server := s.createServerWithMetadata(serverJSON, existingServerVersions, publishTime, isNewLatest)
|
||||
|
||||
// Insert new server version
|
||||
return s.db.CreateServer(txCtx, tx, &server)
|
||||
// CreateServer creates a new server version
|
||||
func (s *registryServiceImpl) CreateServer(ctx context.Context, req *apiv0.ServerJSON) (*apiv0.ServerResponse, error) {
|
||||
// Wrap the entire operation in a transaction
|
||||
return database.InTransactionT(ctx, s.db, func(ctx context.Context, tx pgx.Tx) (*apiv0.ServerResponse, error) {
|
||||
return s.createServerInTransaction(ctx, tx, req)
|
||||
})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
// createServerInTransaction contains the actual CreateServer logic within a transaction
|
||||
func (s *registryServiceImpl) createServerInTransaction(ctx context.Context, tx pgx.Tx, req *apiv0.ServerJSON) (*apiv0.ServerResponse, error) {
|
||||
// Validate the request
|
||||
if err := validators.ValidatePublishRequest(ctx, *req, s.cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
publishTime := time.Now()
|
||||
serverJSON := *req
|
||||
|
||||
// createServerWithMetadata creates a server with proper metadata including server_id and version_id
|
||||
func (s *registryServiceImpl) createServerWithMetadata(
|
||||
serverJSON apiv0.ServerJSON,
|
||||
existingServerVersions []*apiv0.ServerJSON,
|
||||
publishTime time.Time,
|
||||
isNewLatest bool,
|
||||
) apiv0.ServerJSON {
|
||||
server := serverJSON // Copy the input
|
||||
|
||||
// Initialize meta if not present
|
||||
if server.Meta == nil {
|
||||
server.Meta = &apiv0.ServerMeta{}
|
||||
// Acquire advisory lock to prevent concurrent publishes of the same server
|
||||
if err := s.db.AcquirePublishLock(ctx, tx, serverJSON.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Determine server_id - either from existing versions or generate new one
|
||||
var serverID string
|
||||
if len(existingServerVersions) > 0 {
|
||||
// Use existing server_id from any existing version
|
||||
firstExisting := existingServerVersions[0]
|
||||
if firstExisting.Meta != nil && firstExisting.Meta.Official != nil {
|
||||
serverID = firstExisting.Meta.Official.ServerID
|
||||
// Check for duplicate remote URLs
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, tx, serverJSON); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check we haven't exceeded the maximum versions allowed for a server
|
||||
versionCount, err := s.db.CountServerVersions(ctx, tx, serverJSON.Name)
|
||||
if err != nil && !errors.Is(err, database.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
if versionCount >= maxServerVersionsPerServer {
|
||||
return nil, database.ErrMaxServersReached
|
||||
}
|
||||
|
||||
// Check this isn't a duplicate version
|
||||
versionExists, err := s.db.CheckVersionExists(ctx, tx, serverJSON.Name, serverJSON.Version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if versionExists {
|
||||
return nil, database.ErrInvalidVersion
|
||||
}
|
||||
|
||||
// Get current latest version to determine if new version should be latest
|
||||
currentLatest, err := s.db.GetCurrentLatestVersion(ctx, tx, serverJSON.Name)
|
||||
if err != nil && !errors.Is(err, database.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Determine if this version should be marked as latest
|
||||
isNewLatest := true
|
||||
if currentLatest != nil {
|
||||
var existingPublishedAt time.Time
|
||||
if currentLatest.Meta.Official != nil {
|
||||
existingPublishedAt = currentLatest.Meta.Official.PublishedAt
|
||||
}
|
||||
isNewLatest = CompareVersions(
|
||||
serverJSON.Version,
|
||||
currentLatest.Server.Version,
|
||||
publishTime,
|
||||
existingPublishedAt,
|
||||
) > 0
|
||||
}
|
||||
|
||||
// Unmark old latest version if needed
|
||||
if isNewLatest && currentLatest != nil {
|
||||
if err := s.db.UnmarkAsLatest(ctx, tx, serverJSON.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if serverID == "" {
|
||||
// This is the first version of a new server
|
||||
serverID = uuid.New().String()
|
||||
}
|
||||
|
||||
// Set registry metadata
|
||||
server.Meta.Official = &apiv0.RegistryExtensions{
|
||||
ServerID: serverID,
|
||||
VersionID: uuid.New().String(),
|
||||
// Create metadata for the new server
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive, /* New versions are active by default */
|
||||
PublishedAt: publishTime,
|
||||
UpdatedAt: publishTime,
|
||||
IsLatest: isNewLatest,
|
||||
}
|
||||
|
||||
return server
|
||||
// Insert new server version
|
||||
return s.db.CreateServer(ctx, tx, &serverJSON, officialMeta)
|
||||
}
|
||||
|
||||
// validateNoDuplicateRemoteURLs checks that no other server is using the same remote URLs
|
||||
|
|
@ -252,15 +169,15 @@ func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context,
|
|||
// Use filter to find servers with this remote URL
|
||||
filter := &database.ServerFilter{RemoteURL: &remote.URL}
|
||||
|
||||
conflictingServers, _, err := s.db.List(ctx, tx, filter, "", 1000)
|
||||
conflictingServers, _, err := s.db.ListServers(ctx, tx, filter, "", 1000)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to check remote URL conflict: %w", err)
|
||||
}
|
||||
|
||||
// Check if any conflicting server has a different name
|
||||
for _, conflictingServer := range conflictingServers {
|
||||
if conflictingServer.Name != serverDetail.Name {
|
||||
return fmt.Errorf("remote URL %s is already used by server %s", remote.URL, conflictingServer.Name)
|
||||
if conflictingServer.Server.Name != serverDetail.Name {
|
||||
return fmt.Errorf("remote URL %s is already used by server %s", remote.URL, conflictingServer.Server.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -268,62 +185,83 @@ func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context,
|
|||
return nil
|
||||
}
|
||||
|
||||
// getCurrentLatestVersion finds the current latest version from existing server versions
|
||||
func (s *registryServiceImpl) getCurrentLatestVersion(existingServerVersions []*apiv0.ServerJSON) *apiv0.ServerJSON {
|
||||
for _, server := range existingServerVersions {
|
||||
if server.Meta != nil && server.Meta.Official != nil &&
|
||||
server.Meta.Official.IsLatest {
|
||||
return server
|
||||
}
|
||||
}
|
||||
return nil
|
||||
// UpdateServer updates an existing server with new details
|
||||
func (s *registryServiceImpl) UpdateServer(ctx context.Context, serverName, version string, req *apiv0.ServerJSON, newStatus *string) (*apiv0.ServerResponse, error) {
|
||||
// Wrap the entire operation in a transaction
|
||||
return database.InTransactionT(ctx, s.db, func(ctx context.Context, tx pgx.Tx) (*apiv0.ServerResponse, error) {
|
||||
return s.updateServerInTransaction(ctx, tx, serverName, version, req, newStatus)
|
||||
})
|
||||
}
|
||||
|
||||
// EditServer updates an existing server with new details (admin operation)
|
||||
func (s *registryServiceImpl) EditServer(versionID string, req apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Validate the request
|
||||
if err := validators.ValidatePublishRequest(req, s.cfg); err != nil {
|
||||
// updateServerInTransaction contains the actual UpdateServer logic within a transaction
|
||||
func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx pgx.Tx, serverName, version string, req *apiv0.ServerJSON, newStatus *string) (*apiv0.ServerResponse, error) {
|
||||
// Get current server to check if it's deleted or being deleted
|
||||
currentServer, err := s.db.GetServerByNameAndVersion(ctx, tx, serverName, version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return database.InTransactionT(ctx, s.db, func(txCtx context.Context, tx pgx.Tx) (*apiv0.ServerJSON, error) {
|
||||
// Get the current server to preserve metadata
|
||||
currentServer, err := s.db.GetByVersionID(txCtx, tx, versionID)
|
||||
// Skip registry validation if:
|
||||
// 1. Server is currently deleted, OR
|
||||
// 2. Server is being set to deleted status
|
||||
currentlyDeleted := currentServer.Meta.Official != nil && currentServer.Meta.Official.Status == model.StatusDeleted
|
||||
beingDeleted := newStatus != nil && *newStatus == string(model.StatusDeleted)
|
||||
skipRegistryValidation := currentlyDeleted || beingDeleted
|
||||
|
||||
// Validate the request, potentially skipping registry validation for deleted servers
|
||||
if err := s.validateUpdateRequest(ctx, *req, skipRegistryValidation); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Acquire advisory lock to prevent concurrent edits of servers with same name
|
||||
if err := s.db.AcquirePublishLock(ctx, tx, serverName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Merge the request with the current server, preserving metadata
|
||||
updatedServer := *req
|
||||
|
||||
// Check for duplicate remote URLs using the updated server
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, tx, updatedServer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Update server in database
|
||||
updatedServerResponse, err := s.db.UpdateServer(ctx, tx, serverName, version, &updatedServer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Handle status change if provided
|
||||
if newStatus != nil {
|
||||
updatedWithStatus, err := s.db.SetServerStatus(ctx, tx, serverName, version, *newStatus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return updatedWithStatus, nil
|
||||
}
|
||||
|
||||
// Acquire advisory lock to prevent concurrent edits of servers with same name
|
||||
if err := s.db.AcquirePublishLock(txCtx, tx, currentServer.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Merge the request with the current server, preserving metadata
|
||||
updatedServer := *currentServer
|
||||
|
||||
// Update only the user-modifiable fields from the request
|
||||
updatedServer.Name = req.Name
|
||||
updatedServer.Description = req.Description
|
||||
updatedServer.Version = req.Version
|
||||
updatedServer.Status = req.Status
|
||||
updatedServer.Repository = req.Repository
|
||||
updatedServer.Remotes = req.Remotes
|
||||
updatedServer.Packages = req.Packages
|
||||
|
||||
// Update the UpdatedAt timestamp in metadata
|
||||
if updatedServer.Meta != nil && updatedServer.Meta.Official != nil {
|
||||
updatedServer.Meta.Official.UpdatedAt = time.Now()
|
||||
}
|
||||
|
||||
// Check for duplicate remote URLs using the updated server
|
||||
if err := s.validateNoDuplicateRemoteURLs(txCtx, tx, updatedServer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Update server in database
|
||||
return s.db.UpdateServer(txCtx, tx, versionID, &updatedServer)
|
||||
})
|
||||
return updatedServerResponse, nil
|
||||
}
|
||||
|
||||
// validateUpdateRequest validates an update request with optional registry validation skipping
|
||||
func (s *registryServiceImpl) validateUpdateRequest(ctx context.Context, req apiv0.ServerJSON, skipRegistryValidation bool) error {
|
||||
// Always validate the server JSON structure
|
||||
if err := validators.ValidateServerJSON(&req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Skip registry validation if requested (for deleted servers)
|
||||
if skipRegistryValidation || !s.cfg.EnableRegistryValidation {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Perform registry validation for all packages
|
||||
for i, pkg := range req.Packages {
|
||||
if err := validators.ValidatePackage(ctx, pkg, req.Name); err != nil {
|
||||
return fmt.Errorf("registry validation failed for package %d (%s): %w", i, pkg.Identifier, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,15 +6,19 @@ import (
|
|||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
// Create test data
|
||||
existingServers := map[string]*apiv0.ServerJSON{
|
||||
"existing1": {
|
||||
|
|
@ -39,11 +43,10 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Create existing servers using the new CreateServer method
|
||||
for _, server := range existingServers {
|
||||
_, err := service.Publish(*server)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to publish server: %v", err)
|
||||
}
|
||||
_, err := service.CreateServer(ctx, server)
|
||||
require.NoError(t, err, "failed to create server: %v", err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
|
|
@ -65,7 +68,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
{
|
||||
name: "new unique remote URLs - should pass",
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/new-server",
|
||||
Name: "com.example/new-server-unique",
|
||||
Description: "A new server",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
|
|
@ -78,7 +81,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
{
|
||||
name: "duplicate remote URL - should fail",
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/new-server",
|
||||
Name: "com.example/new-server-duplicate",
|
||||
Description: "A new server with duplicate URL",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
|
|
@ -93,7 +96,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/existing-server", // Same name as existing
|
||||
Description: "Updated existing server",
|
||||
Version: "1.1.0",
|
||||
Version: "1.1.0", // Different version
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: "https://api.example.com/mcp"}, // Same URL as before
|
||||
},
|
||||
|
|
@ -104,7 +107,6 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
impl := service.(*registryServiceImpl)
|
||||
|
||||
err := impl.validateNoDuplicateRemoteURLs(ctx, nil, tt.serverDetail)
|
||||
|
|
@ -119,59 +121,55 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestGetByServerID(t *testing.T) {
|
||||
func TestGetServerByName(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Publish multiple versions of the same server
|
||||
server1, err := service.Publish(apiv0.ServerJSON{
|
||||
// Create multiple versions of the same server
|
||||
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "Test server v1",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = service.Publish(apiv0.ServerJSON{
|
||||
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "Test server v2",
|
||||
Version: "2.0.0",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverID string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorMsg string
|
||||
checkResult func(*testing.T, *apiv0.ServerJSON)
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "get latest version by server ID",
|
||||
serverID: server1.Meta.Official.ServerID,
|
||||
name: "get latest version by server name",
|
||||
serverName: "com.example/test-server",
|
||||
expectError: false,
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerJSON) {
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "2.0.0", result.Version) // Should get latest version
|
||||
assert.Equal(t, "Test server v2", result.Description)
|
||||
assert.Equal(t, "2.0.0", result.Server.Version) // Should get latest version
|
||||
assert.Equal(t, "Test server v2", result.Server.Description)
|
||||
assert.True(t, result.Meta.Official.IsLatest)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverID: "00000000-0000-0000-0000-000000000000",
|
||||
serverName: "com.example/non-existent",
|
||||
expectError: true,
|
||||
errorMsg: "record not found",
|
||||
},
|
||||
{
|
||||
name: "invalid server ID format",
|
||||
serverID: "invalid-uuid",
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.GetByServerID(tt.serverID)
|
||||
result, err := service.GetServerByName(ctx, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
|
|
@ -190,82 +188,79 @@ func TestGetByServerID(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestGetByServerIDAndVersion(t *testing.T) {
|
||||
func TestGetServerByNameAndVersion(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Publish multiple versions of the same server
|
||||
server1, err := service.Publish(apiv0.ServerJSON{
|
||||
Name: "com.example/versioned-server",
|
||||
serverName := "com.example/versioned-server"
|
||||
|
||||
// Create multiple versions of the same server
|
||||
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Versioned server v1",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = service.Publish(apiv0.ServerJSON{
|
||||
Name: "com.example/versioned-server",
|
||||
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Versioned server v2",
|
||||
Version: "2.0.0",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverID string
|
||||
serverName string
|
||||
version string
|
||||
expectError bool
|
||||
errorMsg string
|
||||
checkResult func(*testing.T, *apiv0.ServerJSON)
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "get specific version 1.0.0",
|
||||
serverID: server1.Meta.Official.ServerID,
|
||||
serverName: serverName,
|
||||
version: "1.0.0",
|
||||
expectError: false,
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerJSON) {
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "1.0.0", result.Version)
|
||||
assert.Equal(t, "Versioned server v1", result.Description)
|
||||
assert.Equal(t, "1.0.0", result.Server.Version)
|
||||
assert.Equal(t, "Versioned server v1", result.Server.Description)
|
||||
assert.False(t, result.Meta.Official.IsLatest)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "get specific version 2.0.0",
|
||||
serverID: server1.Meta.Official.ServerID,
|
||||
serverName: serverName,
|
||||
version: "2.0.0",
|
||||
expectError: false,
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerJSON) {
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "2.0.0", result.Version)
|
||||
assert.Equal(t, "Versioned server v2", result.Description)
|
||||
assert.Equal(t, "2.0.0", result.Server.Version)
|
||||
assert.Equal(t, "Versioned server v2", result.Server.Description)
|
||||
assert.True(t, result.Meta.Official.IsLatest)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "version not found",
|
||||
serverID: server1.Meta.Official.ServerID,
|
||||
serverName: serverName,
|
||||
version: "3.0.0",
|
||||
expectError: true,
|
||||
errorMsg: "record not found",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverID: "00000000-0000-0000-0000-000000000000",
|
||||
serverName: "com.example/non-existent",
|
||||
version: "1.0.0",
|
||||
expectError: true,
|
||||
errorMsg: "record not found",
|
||||
},
|
||||
{
|
||||
name: "invalid server ID format",
|
||||
serverID: "invalid-uuid",
|
||||
version: "1.0.0",
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.GetByServerIDAndVersion(tt.serverID, tt.version)
|
||||
result, err := service.GetServerByNameAndVersion(ctx, tt.serverName, tt.version)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
|
|
@ -284,44 +279,47 @@ func TestGetByServerIDAndVersion(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestGetAllVersionsByServerID(t *testing.T) {
|
||||
func TestGetAllVersionsByServerName(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Publish multiple versions of the same server
|
||||
server1, err := service.Publish(apiv0.ServerJSON{
|
||||
Name: "com.example/multi-version-server",
|
||||
serverName := "com.example/multi-version-server"
|
||||
|
||||
// Create multiple versions of the same server
|
||||
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Multi-version server v1",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = service.Publish(apiv0.ServerJSON{
|
||||
Name: "com.example/multi-version-server",
|
||||
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Multi-version server v2",
|
||||
Version: "2.0.0",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = service.Publish(apiv0.ServerJSON{
|
||||
Name: "com.example/multi-version-server",
|
||||
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Multi-version server v2.1",
|
||||
Version: "2.1.0",
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverID string
|
||||
serverName string
|
||||
expectError bool
|
||||
errorMsg string
|
||||
checkResult func(*testing.T, []apiv0.ServerJSON)
|
||||
checkResult func(*testing.T, []*apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "get all versions of server",
|
||||
serverID: server1.Meta.Official.ServerID,
|
||||
serverName: serverName,
|
||||
expectError: false,
|
||||
checkResult: func(t *testing.T, result []apiv0.ServerJSON) {
|
||||
checkResult: func(t *testing.T, result []*apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Len(t, result, 3)
|
||||
|
||||
|
|
@ -329,9 +327,8 @@ func TestGetAllVersionsByServerID(t *testing.T) {
|
|||
versions := make([]string, 0, len(result))
|
||||
latestCount := 0
|
||||
for _, server := range result {
|
||||
versions = append(versions, server.Version)
|
||||
assert.Equal(t, server1.Meta.Official.ServerID, server.Meta.Official.ServerID)
|
||||
assert.Equal(t, "com.example/multi-version-server", server.Name)
|
||||
versions = append(versions, server.Server.Version)
|
||||
assert.Equal(t, serverName, server.Server.Name)
|
||||
if server.Meta.Official.IsLatest {
|
||||
latestCount++
|
||||
}
|
||||
|
|
@ -348,20 +345,15 @@ func TestGetAllVersionsByServerID(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverID: "00000000-0000-0000-0000-000000000000",
|
||||
serverName: "com.example/non-existent",
|
||||
expectError: true,
|
||||
errorMsg: "record not found",
|
||||
},
|
||||
{
|
||||
name: "invalid server ID format",
|
||||
serverID: "invalid-uuid",
|
||||
expectError: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.GetAllVersionsByServerID(tt.serverID)
|
||||
result, err := service.GetAllVersionsByServerName(ctx, tt.serverName)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
|
|
@ -380,21 +372,23 @@ func TestGetAllVersionsByServerID(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestPublishConcurrentVersionsNoRace(t *testing.T) {
|
||||
func TestCreateServerConcurrentVersionsNoRace(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
const concurrency = 100
|
||||
results := make([]*apiv0.ServerJSON, concurrency)
|
||||
serverName := "com.example/test-concurrent"
|
||||
results := make([]*apiv0.ServerResponse, concurrency)
|
||||
errors := make([]error, concurrency)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := range concurrency {
|
||||
for i := 0; i < concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func(idx int) {
|
||||
defer wg.Done()
|
||||
result, err := service.Publish(apiv0.ServerJSON{
|
||||
Name: "com.example/test-concurrent",
|
||||
result, err := service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: fmt.Sprintf("Version %d", idx),
|
||||
Version: fmt.Sprintf("1.0.%d", idx),
|
||||
})
|
||||
|
|
@ -404,40 +398,372 @@ func TestPublishConcurrentVersionsNoRace(t *testing.T) {
|
|||
}
|
||||
wg.Wait()
|
||||
|
||||
// All publishes should succeed
|
||||
for i, err := range errors {
|
||||
assert.NoError(t, err, "publish %d failed", i)
|
||||
assert.NoError(t, err, "create server %d failed", i)
|
||||
}
|
||||
|
||||
var sharedServerID string
|
||||
// All results should have the same server name
|
||||
for i, result := range results {
|
||||
if result != nil && result.Meta != nil && result.Meta.Official != nil {
|
||||
if sharedServerID == "" {
|
||||
sharedServerID = result.Meta.Official.ServerID
|
||||
}
|
||||
assert.Equal(t, sharedServerID, result.Meta.Official.ServerID,
|
||||
"version %d has different serverID", i)
|
||||
if result != nil {
|
||||
assert.Equal(t, serverName, result.Server.Name, "version %d has different server name", i)
|
||||
}
|
||||
}
|
||||
|
||||
// Query database to check the final state after all publishes complete
|
||||
// This is necessary because the returned results reflect state at publish time,
|
||||
// but concurrent publishes may have updated the latest flag since then
|
||||
filter := &database.ServerFilter{Name: strPtr("com.example/test-concurrent")}
|
||||
dbResults, _, err := testDB.List(context.Background(), nil, filter, "", 1000)
|
||||
assert.NoError(t, err, "failed to query database")
|
||||
// Query database to check the final state after all creates complete
|
||||
allVersions, err := service.GetAllVersionsByServerName(ctx, serverName)
|
||||
require.NoError(t, err, "failed to get all versions")
|
||||
|
||||
latestCount := 0
|
||||
var latestVersion string
|
||||
for _, r := range dbResults {
|
||||
if r.Meta != nil && r.Meta.Official != nil && r.Meta.Official.IsLatest {
|
||||
for _, r := range allVersions {
|
||||
if r.Meta.Official.IsLatest {
|
||||
latestCount++
|
||||
latestVersion = r.Version
|
||||
latestVersion = r.Server.Version
|
||||
}
|
||||
}
|
||||
|
||||
assert.Equal(t, 1, latestCount, "should have exactly one latest version in database, found version: %s", latestVersion)
|
||||
assert.Len(t, allVersions, concurrency, "should have all %d versions", concurrency)
|
||||
}
|
||||
|
||||
func strPtr(s string) *string {
|
||||
return &s
|
||||
func TestUpdateServer(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
serverName := "com.example/update-test-server"
|
||||
version := "1.0.0"
|
||||
|
||||
// Create initial server
|
||||
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Original description",
|
||||
Version: version,
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: "https://original.example.com/mcp"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
updatedServer *apiv0.ServerJSON
|
||||
newStatus *string
|
||||
expectError bool
|
||||
errorMsg string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "successful server update",
|
||||
serverName: serverName,
|
||||
version: version,
|
||||
updatedServer: &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Updated description",
|
||||
Version: version,
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: "https://updated.example.com/mcp"},
|
||||
},
|
||||
},
|
||||
expectError: false,
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Updated description", result.Server.Description)
|
||||
assert.Len(t, result.Server.Remotes, 1)
|
||||
assert.Equal(t, "https://updated.example.com/mcp", result.Server.Remotes[0].URL)
|
||||
assert.NotZero(t, result.Meta.Official.UpdatedAt)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update with status change",
|
||||
serverName: serverName,
|
||||
version: version,
|
||||
updatedServer: &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Updated with status change",
|
||||
Version: version,
|
||||
},
|
||||
newStatus: stringPtr(string(model.StatusDeprecated)),
|
||||
expectError: false,
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Updated with status change", result.Server.Description)
|
||||
assert.Equal(t, model.StatusDeprecated, result.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update non-existent server",
|
||||
serverName: "com.example/non-existent",
|
||||
version: "1.0.0",
|
||||
updatedServer: &apiv0.ServerJSON{
|
||||
Name: "com.example/non-existent",
|
||||
Description: "Should fail",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
expectError: true,
|
||||
errorMsg: "record not found",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.UpdateServer(ctx, tt.serverName, tt.version, tt.updatedServer, tt.newStatus)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
if tt.errorMsg != "" {
|
||||
assert.Contains(t, err.Error(), tt.errorMsg)
|
||||
}
|
||||
assert.Nil(t, result)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
if tt.checkResult != nil {
|
||||
tt.checkResult(t, result)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateServer_SkipValidationForDeletedServers(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
// Enable registry validation to test that it gets skipped for deleted servers
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: true})
|
||||
|
||||
serverName := "com.example/validation-skip-test"
|
||||
version := "1.0.0"
|
||||
|
||||
// Create server with invalid package configuration (this would fail registry validation)
|
||||
invalidServer := &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Server with invalid package for testing validation skip",
|
||||
Version: version,
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: "npm",
|
||||
Identifier: "non-existent-package-for-validation-test",
|
||||
Version: "1.0.0",
|
||||
Transport: model.Transport{Type: "stdio"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create initial server (validation disabled for creation in this test)
|
||||
originalConfig := service.(*registryServiceImpl).cfg.EnableRegistryValidation
|
||||
service.(*registryServiceImpl).cfg.EnableRegistryValidation = false
|
||||
_, err := service.CreateServer(ctx, invalidServer)
|
||||
require.NoError(t, err, "failed to create server with validation disabled")
|
||||
service.(*registryServiceImpl).cfg.EnableRegistryValidation = originalConfig
|
||||
|
||||
// First, set server to deleted status
|
||||
deletedStatus := string(model.StatusDeleted)
|
||||
_, err = service.UpdateServer(ctx, serverName, version, invalidServer, &deletedStatus)
|
||||
require.NoError(t, err, "should be able to set server to deleted (validation should be skipped)")
|
||||
|
||||
// Verify server is now deleted
|
||||
updatedServer, err := service.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.StatusDeleted, updatedServer.Meta.Official.Status)
|
||||
|
||||
// Now try to update a deleted server - validation should be skipped
|
||||
updatedInvalidServer := &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: "Updated description for deleted server",
|
||||
Version: version,
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: "npm",
|
||||
Identifier: "another-non-existent-package-for-validation-test",
|
||||
Version: "2.0.0",
|
||||
Transport: model.Transport{Type: "stdio"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// This should succeed despite invalid packages because server is deleted
|
||||
result, err := service.UpdateServer(ctx, serverName, version, updatedInvalidServer, nil)
|
||||
assert.NoError(t, err, "updating deleted server should skip registry validation")
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, "Updated description for deleted server", result.Server.Description)
|
||||
assert.Equal(t, model.StatusDeleted, result.Meta.Official.Status)
|
||||
|
||||
// Test updating a server being set to deleted status
|
||||
activeServer := &apiv0.ServerJSON{
|
||||
Name: "com.example/being-deleted-test",
|
||||
Description: "Server being deleted",
|
||||
Version: "1.0.0",
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: "npm",
|
||||
Identifier: "yet-another-non-existent-package",
|
||||
Version: "1.0.0",
|
||||
Transport: model.Transport{Type: "stdio"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create active server (with validation disabled)
|
||||
service.(*registryServiceImpl).cfg.EnableRegistryValidation = false
|
||||
_, err = service.CreateServer(ctx, activeServer)
|
||||
require.NoError(t, err)
|
||||
service.(*registryServiceImpl).cfg.EnableRegistryValidation = originalConfig
|
||||
|
||||
// Update server and set to deleted in same operation - should skip validation
|
||||
newDeletedStatus := string(model.StatusDeleted)
|
||||
result2, err := service.UpdateServer(ctx, "com.example/being-deleted-test", "1.0.0", activeServer, &newDeletedStatus)
|
||||
assert.NoError(t, err, "updating server being set to deleted should skip registry validation")
|
||||
assert.NotNil(t, result2)
|
||||
assert.Equal(t, model.StatusDeleted, result2.Meta.Official.Status)
|
||||
}
|
||||
|
||||
func TestListServers(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Create test servers
|
||||
testServers := []struct {
|
||||
name string
|
||||
version string
|
||||
description string
|
||||
}{
|
||||
{"com.example/server-alpha", "1.0.0", "Alpha server"},
|
||||
{"com.example/server-beta", "1.0.0", "Beta server"},
|
||||
{"com.example/server-gamma", "2.0.0", "Gamma server"},
|
||||
}
|
||||
|
||||
for _, server := range testServers {
|
||||
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: server.name,
|
||||
Description: server.description,
|
||||
Version: server.version,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
filter *database.ServerFilter
|
||||
cursor string
|
||||
limit int
|
||||
expectedCount int
|
||||
expectError bool
|
||||
}{
|
||||
{
|
||||
name: "list all servers",
|
||||
filter: nil,
|
||||
limit: 10,
|
||||
expectedCount: 3,
|
||||
},
|
||||
{
|
||||
name: "filter by name",
|
||||
filter: &database.ServerFilter{
|
||||
Name: stringPtr("com.example/server-alpha"),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 1,
|
||||
},
|
||||
{
|
||||
name: "filter by version",
|
||||
filter: &database.ServerFilter{
|
||||
Version: stringPtr("1.0.0"),
|
||||
},
|
||||
limit: 10,
|
||||
expectedCount: 2,
|
||||
},
|
||||
{
|
||||
name: "pagination with limit",
|
||||
filter: nil,
|
||||
limit: 2,
|
||||
expectedCount: 2,
|
||||
},
|
||||
{
|
||||
name: "cursor pagination",
|
||||
filter: nil,
|
||||
cursor: "com.example/server-alpha",
|
||||
limit: 10,
|
||||
// Should return servers after 'server-alpha' alphabetically
|
||||
expectedCount: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
results, nextCursor, err := service.ListServers(ctx, tt.filter, tt.cursor, tt.limit)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, results, tt.expectedCount)
|
||||
|
||||
// Test cursor behavior
|
||||
if tt.limit < len(testServers) && len(results) == tt.limit {
|
||||
assert.NotEmpty(t, nextCursor, "Should return next cursor when results are limited")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionComparison(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
serverName := "com.example/version-comparison-server"
|
||||
|
||||
// Create versions in non-chronological order to test version comparison logic
|
||||
versions := []struct {
|
||||
version string
|
||||
description string
|
||||
delay time.Duration // Delay to simulate different publish times
|
||||
}{
|
||||
{"2.0.0", "Version 2.0.0", 0},
|
||||
{"1.0.0", "Version 1.0.0", 10 * time.Millisecond},
|
||||
{"2.1.0", "Version 2.1.0", 20 * time.Millisecond},
|
||||
{"1.5.0", "Version 1.5.0", 30 * time.Millisecond},
|
||||
}
|
||||
|
||||
for _, v := range versions {
|
||||
if v.delay > 0 {
|
||||
time.Sleep(v.delay)
|
||||
}
|
||||
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Name: serverName,
|
||||
Description: v.description,
|
||||
Version: v.version,
|
||||
})
|
||||
require.NoError(t, err, "Failed to create version %s", v.version)
|
||||
}
|
||||
|
||||
// Get the latest version - should be 2.1.0 based on semantic versioning
|
||||
latest, err := service.GetServerByName(ctx, serverName)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "2.1.0", latest.Server.Version, "Latest version should be 2.1.0")
|
||||
assert.True(t, latest.Meta.Official.IsLatest)
|
||||
|
||||
// Verify only one version is marked as latest
|
||||
allVersions, err := service.GetAllVersionsByServerName(ctx, serverName)
|
||||
require.NoError(t, err)
|
||||
|
||||
latestCount := 0
|
||||
for _, version := range allVersions {
|
||||
if version.Meta.Official.IsLatest {
|
||||
latestCount++
|
||||
}
|
||||
}
|
||||
assert.Equal(t, 1, latestCount, "Exactly one version should be marked as latest")
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
|
@ -1,24 +1,24 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
)
|
||||
|
||||
// RegistryService defines the interface for registry operations
|
||||
type RegistryService interface {
|
||||
// Retrieve all servers with optional filtering
|
||||
List(filter *database.ServerFilter, cursor string, limit int) ([]apiv0.ServerJSON, string, error)
|
||||
// Retrieve a single server by registry metadata version ID
|
||||
GetByVersionID(versionID string) (*apiv0.ServerJSON, error)
|
||||
// Retrieve latest version of a server by server ID
|
||||
GetByServerID(serverID string) (*apiv0.ServerJSON, error)
|
||||
// Retrieve specific version of a server by server ID and version
|
||||
GetByServerIDAndVersion(serverID string, version string) (*apiv0.ServerJSON, error)
|
||||
// Retrieve all versions of a server by server ID
|
||||
GetAllVersionsByServerID(serverID string) ([]apiv0.ServerJSON, error)
|
||||
// Publish a server
|
||||
Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON, error)
|
||||
// Update an existing server
|
||||
EditServer(id string, req apiv0.ServerJSON) (*apiv0.ServerJSON, error)
|
||||
// ListServers retrieve all servers with optional filtering
|
||||
ListServers(ctx context.Context, filter *database.ServerFilter, cursor string, limit int) ([]*apiv0.ServerResponse, string, error)
|
||||
// GetServerByName retrieve latest version of a server by server name
|
||||
GetServerByName(ctx context.Context, serverName string) (*apiv0.ServerResponse, error)
|
||||
// GetServerByNameAndVersion retrieve specific version of a server by server name and version
|
||||
GetServerByNameAndVersion(ctx context.Context, serverName string, version string) (*apiv0.ServerResponse, error)
|
||||
// GetAllVersionsByServerName retrieve all versions of a server by server name
|
||||
GetAllVersionsByServerName(ctx context.Context, serverName string) ([]*apiv0.ServerResponse, error)
|
||||
// CreateServer creates a new server version
|
||||
CreateServer(ctx context.Context, req *apiv0.ServerJSON) (*apiv0.ServerResponse, error)
|
||||
// UpdateServer updates an existing server and optionally its status
|
||||
UpdateServer(ctx context.Context, serverName, version string, req *apiv0.ServerJSON, newStatus *string) (*apiv0.ServerResponse, error)
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue