Implement flattened _meta format for server extensions (#331)
## Summary This PR implements the flattened `_meta` format for server extensions as discussed in #284, replacing the confusing wrapper format with a clean single-file approach. **Before (wrapper format):** ```json { "server": { "name": "my-server", "description": "..." }, "x-publisher": { "build_info": "..." }, "x-io.modelcontextprotocol.registry": { "id": "...", "published_at": "..." } } ``` **After (flattened format):** ```json { "name": "my-server", "description": "...", "_meta": { "publisher": { "build_info": "..." }, "io.modelcontextprotocol.registry": { "id": "...", "published_at": "..." } } } ``` ## Key Changes - **Flattened Format**: Single `ServerJSON` file with structured `_meta` field - **Better DX**: Publishers maintain one file instead of separate server.json + extensions.json - **MCP Compliance**: Uses standard `_meta` mechanism instead of `x-*` prefixes - **Simplified Database**: PostgreSQL now uses simple `id, value` table structure - **Type Safety**: Structured `ServerMeta` with known extension fields ## Database Migration Added migration `003_simplify_to_key_value.sql` that drops the complex relational structure and creates a simple key-value table. This significantly simplifies database management. ## Testing - All core tests passing (validators, service layer) - Schema validation working for all 10 examples - Seed data successfully migrated (396 entries) - Publishing functionality verified Fixes #284
This commit is contained in:
parent
be036a45ea
commit
218b0b422d
20 changed files with 19375 additions and 19670 deletions
|
|
@ -18,9 +18,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"`
|
||||
ID string `path:"id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
Body apiv0.PublishRequest `body:""`
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token with edit permissions" required:"true"`
|
||||
ID string `path:"id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
Body apiv0.ServerJSON `body:""`
|
||||
}
|
||||
|
||||
// RegisterEditEndpoints registers the edit endpoint
|
||||
|
|
@ -38,7 +38,7 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *EditServerInput) (*Response[apiv0.ServerRecord], error) {
|
||||
}, func(ctx context.Context, input *EditServerInput) (*Response[apiv0.ServerJSON], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
|
|
@ -63,7 +63,7 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
}
|
||||
|
||||
// Verify edit permissions for this server using the existing server name
|
||||
if !jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionEdit, claims.Permissions) {
|
||||
if !jwtManager.HasPermission(currentServer.Name, auth.PermissionActionEdit, claims.Permissions) {
|
||||
return nil, huma.Error403Forbidden("You do not have edit permissions for this server")
|
||||
}
|
||||
|
||||
|
|
@ -73,12 +73,12 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
}
|
||||
|
||||
// Prevent renaming servers
|
||||
if currentServer.Server.Name != input.Body.Server.Name {
|
||||
if currentServer.Name != input.Body.Name {
|
||||
return nil, huma.Error400BadRequest("Cannot rename server")
|
||||
}
|
||||
|
||||
// Prevent undeleting servers - once deleted, they stay deleted
|
||||
if currentServer.Server.Status == model.StatusDeleted && input.Body.Server.Status != model.StatusDeleted {
|
||||
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.")
|
||||
}
|
||||
|
||||
|
|
@ -91,7 +91,7 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
|
|||
return nil, huma.Error400BadRequest("Failed to edit server", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerRecord]{
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
Body: *updatedServer,
|
||||
}, nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -45,40 +45,34 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.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",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.1",
|
||||
},
|
||||
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",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.1",
|
||||
},
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
// Current server (not deleted)
|
||||
currentServer := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
},
|
||||
currentServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
}
|
||||
registry.On("GetByID", "550e8400-e29b-41d4-a716-446655440001").Return(currentServer, nil)
|
||||
|
||||
expectedResponse := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
Status: model.StatusDeprecated,
|
||||
},
|
||||
expectedResponse := &apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
Status: model.StatusDeprecated,
|
||||
}
|
||||
registry.On("EditServer", "550e8400-e29b-41d4-a716-446655440001", mock.AnythingOfType("v0.PublishRequest")).Return(expectedResponse, nil)
|
||||
registry.On("EditServer", "550e8400-e29b-41d4-a716-446655440001", mock.AnythingOfType("v0.ServerJSON")).Return(expectedResponse, nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
|
|
@ -86,36 +80,32 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
name: "missing authorization header",
|
||||
serverID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
authHeader: "",
|
||||
requestBody: apiv0.PublishRequest{},
|
||||
requestBody: apiv0.ServerJSON{},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: 422,
|
||||
expectedError: "required header parameter is missing",
|
||||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
serverID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
name: "invalid authorization header format",
|
||||
serverID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Unauthorized",
|
||||
},
|
||||
{
|
||||
name: "invalid token",
|
||||
serverID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
authHeader: "Bearer invalid-token",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
name: "invalid token",
|
||||
serverID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
authHeader: "Bearer invalid-token",
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
|
|
@ -135,20 +125,16 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
// Need to mock GetByID since we check permissions against existing server name
|
||||
currentServer := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
},
|
||||
currentServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
}
|
||||
registry.On("GetByID", "550e8400-e29b-41d4-a716-446655440001").Return(currentServer, nil)
|
||||
},
|
||||
|
|
@ -169,21 +155,17 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
// Need to mock GetByID since we check permissions against existing server name
|
||||
// This test case shows a different scenario: existing server is "other" but user only has perms for "domdomegg"
|
||||
currentServer := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
},
|
||||
currentServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
}
|
||||
registry.On("GetByID", "550e8400-e29b-41d4-a716-446655440001").Return(currentServer, nil)
|
||||
},
|
||||
|
|
@ -204,11 +186,9 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
registry.On("GetByID", "550e8400-e29b-41d4-a716-446655440001").Return(nil, database.ErrNotFound)
|
||||
|
|
@ -230,23 +210,19 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Updated test server",
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
// Current server (not deleted)
|
||||
currentServer := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
},
|
||||
currentServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
}
|
||||
registry.On("GetByID", "550e8400-e29b-41d4-a716-446655440001").Return(currentServer, nil)
|
||||
registry.On("EditServer", "550e8400-e29b-41d4-a716-446655440001", mock.AnythingOfType("v0.PublishRequest")).Return(nil, errors.New("database error"))
|
||||
registry.On("EditServer", "550e8400-e29b-41d4-a716-446655440001", mock.AnythingOfType("v0.ServerJSON")).Return(nil, errors.New("database error"))
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Bad Request",
|
||||
|
|
@ -265,20 +241,16 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "invalid-name-format", // Missing namespace/name format
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "invalid-name-format", // Missing namespace/name format
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
currentServer := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
},
|
||||
currentServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusActive,
|
||||
}
|
||||
registry.On("GetByID", "550e8400-e29b-41d4-a716-446655440001").Return(currentServer, nil)
|
||||
},
|
||||
|
|
@ -299,21 +271,17 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
})
|
||||
return "Bearer " + token
|
||||
}(),
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Trying to undelete server",
|
||||
Status: model.StatusActive,
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Trying to undelete server",
|
||||
Status: model.StatusActive,
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
// Current server is deleted
|
||||
currentServer := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusDeleted,
|
||||
},
|
||||
currentServer := &apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Original server",
|
||||
Status: model.StatusDeleted,
|
||||
}
|
||||
registry.On("GetByID", "550e8400-e29b-41d4-a716-446655440001").Return(currentServer, nil)
|
||||
},
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ import (
|
|||
|
||||
// PublishServerInput represents the input for publishing a server
|
||||
type PublishServerInput struct {
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token (obtained from /v0/auth/token/github)" required:"true"`
|
||||
Body apiv0.PublishRequest `body:""`
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token (obtained from /v0/auth/token/github)" required:"true"`
|
||||
Body apiv0.ServerJSON `body:""`
|
||||
}
|
||||
|
||||
// RegisterPublishEndpoint registers the publish endpoint
|
||||
|
|
@ -34,7 +34,7 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
|
|||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *PublishServerInput) (*Response[apiv0.ServerRecord], error) {
|
||||
}, func(ctx context.Context, input *PublishServerInput) (*Response[apiv0.ServerJSON], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
|
|
@ -55,7 +55,7 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
|
|||
}
|
||||
|
||||
// Verify that the token has permission to publish the server
|
||||
if !jwtManager.HasPermission(input.Body.Server.Name, auth.PermissionActionPublish, claims.Permissions) {
|
||||
if !jwtManager.HasPermission(input.Body.Name, auth.PermissionActionPublish, claims.Permissions) {
|
||||
return nil, huma.Error403Forbidden("You do not have permission to publish this server")
|
||||
}
|
||||
|
||||
|
|
@ -65,8 +65,8 @@ func RegisterPublishEndpoint(api huma.API, registry service.RegistryService, cfg
|
|||
return nil, huma.Error400BadRequest("Failed to publish server", err)
|
||||
}
|
||||
|
||||
// Return the published server in extension wrapper format
|
||||
return &Response[apiv0.ServerRecord]{
|
||||
// Return the published server in flattened format
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
Body: *publishedServer,
|
||||
}, nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -54,18 +54,16 @@ func TestPublishIntegration(t *testing.T) {
|
|||
v0.RegisterPublishEndpoint(api, registryService, testConfig)
|
||||
|
||||
t.Run("successful publish with GitHub auth", func(t *testing.T) {
|
||||
publishReq := apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.testuser/test-mcp-server",
|
||||
Description: "A test MCP server for integration testing",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/test-mcp-server",
|
||||
Source: "github",
|
||||
ID: "testuser/test-mcp-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
publishReq := apiv0.ServerJSON{
|
||||
Name: "io.github.testuser/test-mcp-server",
|
||||
Description: "A test MCP server for integration testing",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/testuser/test-mcp-server",
|
||||
Source: "github",
|
||||
ID: "testuser/test-mcp-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -92,27 +90,25 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerRecord
|
||||
var response apiv0.ServerJSON
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Server.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Server.VersionDetail.Version, response.Server.VersionDetail.Version)
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
assert.Equal(t, publishReq.VersionDetail.Version, response.VersionDetail.Version)
|
||||
})
|
||||
|
||||
t.Run("successful publish with none auth (no prefix)", func(t *testing.T) {
|
||||
publishReq := apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "com.example/test-mcp-server-no-auth",
|
||||
Description: "A test MCP server without authentication",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
publishReq := apiv0.ServerJSON{
|
||||
Name: "com.example/test-mcp-server-no-auth",
|
||||
Description: "A test MCP server without authentication",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -138,18 +134,16 @@ func TestPublishIntegration(t *testing.T) {
|
|||
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
|
||||
var response apiv0.ServerRecord
|
||||
var response apiv0.ServerJSON
|
||||
err = json.Unmarshal(rr.Body.Bytes(), &response)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, publishReq.Server.Name, response.Server.Name)
|
||||
assert.Equal(t, publishReq.Name, response.Name)
|
||||
})
|
||||
|
||||
t.Run("publish fails with missing authorization header", func(t *testing.T) {
|
||||
publishReq := apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server",
|
||||
},
|
||||
publishReq := apiv0.ServerJSON{
|
||||
Name: "test-server",
|
||||
}
|
||||
|
||||
body, err := json.Marshal(publishReq)
|
||||
|
|
@ -167,12 +161,10 @@ func TestPublishIntegration(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("publish fails with invalid token", func(t *testing.T) {
|
||||
publishReq := apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
publishReq := apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
}
|
||||
|
||||
body, err := json.Marshal(publishReq)
|
||||
|
|
@ -190,18 +182,16 @@ func TestPublishIntegration(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("publish fails when permission denied", func(t *testing.T) {
|
||||
publishReq := apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
publishReq := apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,33 +29,33 @@ type MockRegistryService struct {
|
|||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockRegistryService) List(cursor string, limit int) ([]apiv0.ServerRecord, string, error) {
|
||||
func (m *MockRegistryService) List(cursor string, limit int) ([]apiv0.ServerJSON, string, error) {
|
||||
args := m.Called(cursor, limit)
|
||||
return args.Get(0).([]apiv0.ServerRecord), args.String(1), args.Error(2)
|
||||
return args.Get(0).([]apiv0.ServerJSON), args.String(1), args.Error(2)
|
||||
}
|
||||
|
||||
func (m *MockRegistryService) GetByID(id string) (*apiv0.ServerRecord, error) {
|
||||
func (m *MockRegistryService) GetByID(id string) (*apiv0.ServerJSON, error) {
|
||||
args := m.Called(id)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*apiv0.ServerRecord), args.Error(1)
|
||||
return args.Get(0).(*apiv0.ServerJSON), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockRegistryService) Publish(request apiv0.PublishRequest) (*apiv0.ServerRecord, error) {
|
||||
func (m *MockRegistryService) Publish(request apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
args := m.Called(request)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*apiv0.ServerRecord), args.Error(1)
|
||||
return args.Get(0).(*apiv0.ServerJSON), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockRegistryService) EditServer(id string, request apiv0.PublishRequest) (*apiv0.ServerRecord, error) {
|
||||
func (m *MockRegistryService) EditServer(id string, request apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
args := m.Called(id, request)
|
||||
if args.Get(0) == nil {
|
||||
return nil, args.Error(1)
|
||||
}
|
||||
return args.Get(0).(*apiv0.ServerRecord), args.Error(1)
|
||||
return args.Get(0).(*apiv0.ServerJSON), args.Error(1)
|
||||
}
|
||||
|
||||
// Helper function to generate a valid JWT token for testing
|
||||
|
|
@ -88,18 +88,16 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
}{
|
||||
{
|
||||
name: "successful publish with GitHub auth",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
},
|
||||
tokenClaims: &auth.JWTClaims{
|
||||
|
|
@ -110,24 +108,22 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
},
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
registry.On("Publish", mock.AnythingOfType("v0.PublishRequest")).Return(&apiv0.ServerRecord{}, nil)
|
||||
registry.On("Publish", mock.AnythingOfType("v0.ServerJSON")).Return(&apiv0.ServerJSON{}, nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "successful publish with no auth (AuthMethodNone)",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "example/test-server",
|
||||
Description: "A test server without auth",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "example/test-server",
|
||||
Description: "A test server without auth",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
},
|
||||
tokenClaims: &auth.JWTClaims{
|
||||
|
|
@ -137,13 +133,13 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
},
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
registry.On("Publish", mock.AnythingOfType("v0.PublishRequest")).Return(&apiv0.ServerRecord{}, nil)
|
||||
registry.On("Publish", mock.AnythingOfType("v0.ServerJSON")).Return(&apiv0.ServerJSON{}, nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
requestBody: apiv0.PublishRequest{},
|
||||
requestBody: apiv0.ServerJSON{},
|
||||
authHeader: "", // Empty auth header
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
|
|
@ -151,12 +147,10 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.domdomegg/test-server",
|
||||
Description: "Test server",
|
||||
VersionDetail: model.VersionDetail{Version: "1.0.0"},
|
||||
},
|
||||
authHeader: "InvalidFormat",
|
||||
setupMocks: func(_ *MockRegistryService) {},
|
||||
|
|
@ -165,13 +159,11 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "invalid token",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
},
|
||||
authHeader: "Bearer invalidToken",
|
||||
|
|
@ -181,18 +173,16 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "permission denied",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "io.github.other/test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
},
|
||||
tokenClaims: &auth.JWTClaims{
|
||||
|
|
@ -207,18 +197,16 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "registry service error",
|
||||
requestBody: apiv0.PublishRequest{
|
||||
Server: model.ServerJSON{
|
||||
Name: "example/test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Name: "example/test-server",
|
||||
Description: "A test server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server",
|
||||
Source: "github",
|
||||
ID: "example/test-server",
|
||||
},
|
||||
},
|
||||
tokenClaims: &auth.JWTClaims{
|
||||
|
|
@ -228,7 +216,7 @@ func TestPublishEndpoint(t *testing.T) {
|
|||
},
|
||||
},
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
registry.On("Publish", mock.AnythingOfType("v0.PublishRequest")).Return(nil, errors.New("cannot publish duplicate version"))
|
||||
registry.On("Publish", mock.AnythingOfType("v0.ServerJSON")).Return(nil, errors.New("cannot publish duplicate version"))
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Failed to publish server",
|
||||
|
|
|
|||
|
|
@ -25,8 +25,8 @@ type ListServersInput struct {
|
|||
|
||||
// ListServersBody represents the paginated server list response body
|
||||
type ListServersBody struct {
|
||||
Servers []apiv0.ServerRecord `json:"servers" doc:"List of MCP servers with extensions"`
|
||||
Metadata *Metadata `json:"metadata,omitempty" doc:"Pagination metadata"`
|
||||
Servers []apiv0.ServerJSON `json:"servers" doc:"List of MCP servers with extensions"`
|
||||
Metadata *Metadata `json:"metadata,omitempty" doc:"Pagination metadata"`
|
||||
}
|
||||
|
||||
// ServerDetailInput represents the input for getting server details
|
||||
|
|
@ -85,7 +85,7 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
Summary: "Get MCP server details",
|
||||
Description: "Get detailed information about a specific MCP server",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ServerDetailInput) (*Response[apiv0.ServerRecord], error) {
|
||||
}, func(_ context.Context, input *ServerDetailInput) (*Response[apiv0.ServerJSON], error) {
|
||||
// Get the server details from the registry service
|
||||
serverDetail, err := registry.GetByID(input.ID)
|
||||
if err != nil {
|
||||
|
|
@ -95,7 +95,7 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
|||
return nil, huma.Error500InternalServerError("Failed to get server details", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerRecord]{
|
||||
return &Response[apiv0.ServerJSON]{
|
||||
Body: *serverDetail,
|
||||
}, nil
|
||||
})
|
||||
|
|
|
|||
|
|
@ -24,55 +24,15 @@ func TestServersListEndpoint(t *testing.T) {
|
|||
queryParams string
|
||||
setupMocks func(*MockRegistryService)
|
||||
expectedStatus int
|
||||
expectedServers []apiv0.ServerRecord
|
||||
expectedServers []apiv0.ServerJSON
|
||||
expectedMeta *v0.Metadata
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "successful list with default parameters",
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
servers := []apiv0.ServerRecord{
|
||||
servers := []apiv0.ServerJSON{
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server-1",
|
||||
Description: "First test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-1",
|
||||
Source: "github",
|
||||
ID: "example/test-server-1",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
},
|
||||
},
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server-2",
|
||||
Description: "Second test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-2",
|
||||
Source: "github",
|
||||
ID: "example/test-server-2",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "2.0.0",
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440002",
|
||||
},
|
||||
},
|
||||
}
|
||||
registry.Mock.On("List", "", 30).Return(servers, "", nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedServers: []apiv0.ServerRecord{
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server-1",
|
||||
Description: "First test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -83,13 +43,13 @@ func TestServersListEndpoint(t *testing.T) {
|
|||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
},
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
},
|
||||
},
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
{
|
||||
Name: "test-server-2",
|
||||
Description: "Second test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -100,9 +60,49 @@ func TestServersListEndpoint(t *testing.T) {
|
|||
VersionDetail: model.VersionDetail{
|
||||
Version: "2.0.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440002",
|
||||
},
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440002",
|
||||
}
|
||||
registry.Mock.On("List", "", 30).Return(servers, "", nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedServers: []apiv0.ServerJSON{
|
||||
{
|
||||
Name: "test-server-1",
|
||||
Description: "First test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-1",
|
||||
Source: "github",
|
||||
ID: "example/test-server-1",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440001",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "test-server-2",
|
||||
Description: "Second test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-2",
|
||||
Source: "github",
|
||||
ID: "example/test-server-2",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "2.0.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440002",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
@ -111,32 +111,8 @@ func TestServersListEndpoint(t *testing.T) {
|
|||
name: "successful list with cursor and limit",
|
||||
queryParams: "?cursor=550e8400-e29b-41d4-a716-446655440000&limit=10",
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
servers := []apiv0.ServerRecord{
|
||||
servers := []apiv0.ServerJSON{
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server-3",
|
||||
Description: "Third test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-3",
|
||||
Source: "github",
|
||||
ID: "example/test-server-3",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.5.0",
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440003",
|
||||
},
|
||||
},
|
||||
}
|
||||
nextCursor := uuid.New().String()
|
||||
registry.Mock.On("List", mock.AnythingOfType("string"), 10).Return(servers, nextCursor, nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedServers: []apiv0.ServerRecord{
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server-3",
|
||||
Description: "Third test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -147,9 +123,33 @@ func TestServersListEndpoint(t *testing.T) {
|
|||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.5.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440003",
|
||||
},
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440003",
|
||||
}
|
||||
nextCursor := uuid.New().String()
|
||||
registry.Mock.On("List", mock.AnythingOfType("string"), 10).Return(servers, nextCursor, nil)
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedServers: []apiv0.ServerJSON{
|
||||
{
|
||||
Name: "test-server-3",
|
||||
Description: "Third test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-3",
|
||||
Source: "github",
|
||||
ID: "example/test-server-3",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.5.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "550e8400-e29b-41d4-a716-446655440003",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
@ -196,7 +196,7 @@ func TestServersListEndpoint(t *testing.T) {
|
|||
{
|
||||
name: "registry service error",
|
||||
setupMocks: func(registry *MockRegistryService) {
|
||||
registry.Mock.On("List", "", 30).Return([]apiv0.ServerRecord{}, "", errors.New("database connection error"))
|
||||
registry.Mock.On("List", "", 30).Return([]apiv0.ServerJSON{}, "", errors.New("database connection error"))
|
||||
},
|
||||
expectedStatus: http.StatusInternalServerError,
|
||||
expectedError: "Failed to get registry list",
|
||||
|
|
@ -233,8 +233,8 @@ func TestServersListEndpoint(t *testing.T) {
|
|||
|
||||
// Parse response body
|
||||
var resp struct {
|
||||
Servers []apiv0.ServerRecord `json:"servers"`
|
||||
Metadata *v0.Metadata `json:"metadata,omitempty"`
|
||||
Servers []apiv0.ServerJSON `json:"servers"`
|
||||
Metadata *v0.Metadata `json:"metadata,omitempty"`
|
||||
}
|
||||
err := json.NewDecoder(w.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
|
|
@ -268,28 +268,28 @@ func TestServersDetailEndpoint(t *testing.T) {
|
|||
serverID string
|
||||
setupMocks func(*MockRegistryService, string)
|
||||
expectedStatus int
|
||||
expectedServer *apiv0.ServerRecord
|
||||
expectedServer *apiv0.ServerJSON
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "successful get server detail",
|
||||
serverID: uuid.New().String(),
|
||||
setupMocks: func(registry *MockRegistryService, serverID string) {
|
||||
serverDetail := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server-detail",
|
||||
Description: "Test server detail",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-detail",
|
||||
Source: "github",
|
||||
ID: "example/test-server-detail",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "2.0.0",
|
||||
},
|
||||
serverDetail := &apiv0.ServerJSON{
|
||||
Name: "test-server-detail",
|
||||
Description: "Test server detail",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-detail",
|
||||
Source: "github",
|
||||
ID: "example/test-server-detail",
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: serverID,
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "2.0.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: serverID,
|
||||
},
|
||||
},
|
||||
}
|
||||
registry.Mock.On("GetByID", serverID).Return(serverDetail, nil)
|
||||
|
|
@ -352,12 +352,12 @@ func TestServersDetailEndpoint(t *testing.T) {
|
|||
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
|
||||
|
||||
// Parse response body
|
||||
var serverDetailResp apiv0.ServerRecord
|
||||
var serverDetailResp apiv0.ServerJSON
|
||||
err := json.NewDecoder(w.Body).Decode(&serverDetailResp)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Check that we got a valid response
|
||||
assert.NotEmpty(t, serverDetailResp.Server.Name)
|
||||
assert.NotEmpty(t, serverDetailResp.Name)
|
||||
} else if tc.expectedError != "" {
|
||||
// Check error message for non-200 responses
|
||||
assert.Contains(t, w.Body.String(), tc.expectedError)
|
||||
|
|
@ -376,30 +376,27 @@ func TestServersEndpointsIntegration(t *testing.T) {
|
|||
|
||||
// Test data
|
||||
serverID := uuid.New().String()
|
||||
servers := []apiv0.ServerRecord{
|
||||
servers := []apiv0.ServerJSON{
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "integration-test-server",
|
||||
Description: "Integration test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/integration-test",
|
||||
Source: "github",
|
||||
ID: "example/integration-test",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Name: "integration-test-server",
|
||||
Description: "Integration test server",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/integration-test",
|
||||
Source: "github",
|
||||
ID: "example/integration-test",
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: serverID,
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: serverID,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
serverDetail := &apiv0.ServerRecord{
|
||||
Server: servers[0].Server,
|
||||
XIOModelContextProtocolRegistry: servers[0].XIOModelContextProtocolRegistry,
|
||||
}
|
||||
serverDetail := &servers[0]
|
||||
|
||||
// Setup mocks
|
||||
mockRegistry.Mock.On("List", "", 30).Return(servers, "", nil)
|
||||
|
|
@ -439,7 +436,7 @@ func TestServersEndpointsIntegration(t *testing.T) {
|
|||
|
||||
// Parse response body
|
||||
var listResp struct {
|
||||
Servers []apiv0.ServerRecord `json:"servers"`
|
||||
Servers []apiv0.ServerJSON `json:"servers"`
|
||||
}
|
||||
err = json.NewDecoder(resp.Body).Decode(&listResp)
|
||||
assert.NoError(t, err)
|
||||
|
|
@ -470,7 +467,7 @@ func TestServersEndpointsIntegration(t *testing.T) {
|
|||
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
|
||||
|
||||
// Parse response body
|
||||
var serverDetailResp apiv0.ServerRecord
|
||||
var serverDetailResp apiv0.ServerJSON
|
||||
err = json.NewDecoder(resp.Body).Decode(&serverDetailResp)
|
||||
assert.NoError(t, err)
|
||||
|
||||
|
|
|
|||
|
|
@ -20,21 +20,21 @@ import (
|
|||
)
|
||||
|
||||
func mockServerEndpoint(registry *MockRegistryService, serverID string) {
|
||||
serverDetail := &apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "test-server-detail",
|
||||
Description: "Test server detail",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-detail",
|
||||
Source: "github",
|
||||
ID: "example/test-server-detail",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "2.0.0",
|
||||
},
|
||||
serverDetail := &apiv0.ServerJSON{
|
||||
Name: "test-server-detail",
|
||||
Description: "Test server detail",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/example/test-server-detail",
|
||||
Source: "github",
|
||||
ID: "example/test-server-detail",
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: serverID,
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "2.0.0",
|
||||
},
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: serverID,
|
||||
},
|
||||
},
|
||||
}
|
||||
registry.Mock.On("GetByID", serverID).Return(serverDetail, nil)
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@ import (
|
|||
"errors"
|
||||
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// Common database errors
|
||||
|
|
@ -21,16 +20,16 @@ var (
|
|||
// Database defines the interface for database operations with extension wrapper architecture
|
||||
type Database interface {
|
||||
// List retrieves all ServerRecord entries with optional filtering
|
||||
List(ctx context.Context, filter map[string]any, cursor string, limit int) ([]*apiv0.ServerRecord, string, error)
|
||||
List(ctx context.Context, filter map[string]any, cursor string, limit int) ([]*apiv0.ServerJSON, string, error)
|
||||
// GetByID retrieves a single ServerRecord by its ID
|
||||
GetByID(ctx context.Context, id string) (*apiv0.ServerRecord, error)
|
||||
GetByID(ctx context.Context, id string) (*apiv0.ServerJSON, error)
|
||||
// Publish adds a new server to the database with separated server.json and extensions
|
||||
// The registryMetadata contains metadata determined by the service layer (e.g., is_latest, timestamps)
|
||||
Publish(ctx context.Context, serverDetail model.ServerJSON, publisherExtensions map[string]interface{}, registryMetadata apiv0.RegistryExtensions) (*apiv0.ServerRecord, error)
|
||||
Publish(ctx context.Context, serverDetail apiv0.ServerJSON, publisherExtensions map[string]interface{}, registryMetadata apiv0.RegistryExtensions) (*apiv0.ServerJSON, error)
|
||||
// UpdateLatestFlag updates the is_latest flag for a specific server record
|
||||
UpdateLatestFlag(ctx context.Context, id string, isLatest bool) error
|
||||
// UpdateServer updates an existing server record with new server details
|
||||
UpdateServer(ctx context.Context, id string, serverDetail model.ServerJSON, publisherExtensions map[string]interface{}) (*apiv0.ServerRecord, error)
|
||||
UpdateServer(ctx context.Context, id string, serverDetail apiv0.ServerJSON, publisherExtensions map[string]interface{}) (*apiv0.ServerJSON, error)
|
||||
// ImportSeed imports initial data from a seed file
|
||||
ImportSeed(ctx context.Context, seedFilePath string) error
|
||||
// Close closes the database connection
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import (
|
|||
// 2. Direct HTTP URLs to seed.json files - expects extension wrapper format
|
||||
// 3. Registry root URLs (automatically appends /v0/servers and paginates)
|
||||
// Only the extension wrapper format is supported (array of ServerResponse objects)
|
||||
func ReadSeedFile(ctx context.Context, path string) ([]*apiv0.ServerRecord, error) {
|
||||
func ReadSeedFile(ctx context.Context, path string) ([]*apiv0.ServerJSON, error) {
|
||||
var data []byte
|
||||
var err error
|
||||
|
||||
|
|
@ -41,30 +41,30 @@ func ReadSeedFile(ctx context.Context, path string) ([]*apiv0.ServerRecord, erro
|
|||
}
|
||||
|
||||
// Parse extension wrapper format (only supported format)
|
||||
var serverResponses []apiv0.ServerRecord
|
||||
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)
|
||||
}
|
||||
|
||||
if len(serverResponses) == 0 {
|
||||
return []*apiv0.ServerRecord{}, nil
|
||||
return []*apiv0.ServerJSON{}, nil
|
||||
}
|
||||
|
||||
// Validate servers and collect warnings instead of failing the whole batch
|
||||
var validRecords []*apiv0.ServerRecord
|
||||
var validRecords []*apiv0.ServerJSON
|
||||
var invalidServers []string
|
||||
var validationFailures []string
|
||||
|
||||
for _, response := range serverResponses {
|
||||
if err := validators.ValidateServerJSON(&response.Server); err != nil {
|
||||
if err := validators.ValidateServerJSON(&response); err != nil {
|
||||
// Log warning and track invalid server instead of failing
|
||||
invalidServers = append(invalidServers, response.Server.Name)
|
||||
validationFailures = append(validationFailures, fmt.Sprintf("Server '%s': %v", response.Server.Name, err))
|
||||
log.Printf("Warning: Skipping invalid server '%s': %v", response.Server.Name, err)
|
||||
invalidServers = append(invalidServers, response.Name)
|
||||
validationFailures = append(validationFailures, fmt.Sprintf("Server '%s': %v", response.Name, err))
|
||||
log.Printf("Warning: Skipping invalid server '%s': %v", response.Name, err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Convert valid ServerResponse to ServerRecord
|
||||
// Convert valid ServerJSON to ServerRecord
|
||||
record := convertServerResponseToRecord(response)
|
||||
validRecords = append(validRecords, record)
|
||||
}
|
||||
|
|
@ -102,8 +102,8 @@ func fetchFromHTTP(ctx context.Context, url string) ([]byte, error) {
|
|||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func fetchFromRegistryAPI(ctx context.Context, baseURL string) ([]*apiv0.ServerRecord, error) {
|
||||
var allRecords []*apiv0.ServerRecord
|
||||
func fetchFromRegistryAPI(ctx context.Context, baseURL string) ([]*apiv0.ServerJSON, error) {
|
||||
var allRecords []*apiv0.ServerJSON
|
||||
cursor := ""
|
||||
|
||||
for {
|
||||
|
|
@ -122,7 +122,7 @@ func fetchFromRegistryAPI(ctx context.Context, baseURL string) ([]*apiv0.ServerR
|
|||
}
|
||||
|
||||
var response struct {
|
||||
Servers []apiv0.ServerRecord `json:"servers"`
|
||||
Servers []apiv0.ServerJSON `json:"servers"`
|
||||
Metadata *struct {
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
} `json:"metadata,omitempty"`
|
||||
|
|
@ -148,19 +148,8 @@ func fetchFromRegistryAPI(ctx context.Context, baseURL string) ([]*apiv0.ServerR
|
|||
return allRecords, nil
|
||||
}
|
||||
|
||||
func convertServerResponseToRecord(response apiv0.ServerRecord) *apiv0.ServerRecord {
|
||||
// The registry extensions are already properly typed, so we can use them directly
|
||||
registryMetadata := response.XIOModelContextProtocolRegistry
|
||||
|
||||
// Publisher extensions
|
||||
publisherExtensions := response.XPublisher
|
||||
if publisherExtensions == nil {
|
||||
publisherExtensions = make(map[string]interface{})
|
||||
}
|
||||
|
||||
return &apiv0.ServerRecord{
|
||||
Server: response.Server,
|
||||
XIOModelContextProtocolRegistry: registryMetadata,
|
||||
XPublisher: publisherExtensions,
|
||||
}
|
||||
func convertServerResponseToRecord(response apiv0.ServerJSON) *apiv0.ServerJSON {
|
||||
// The response is already in the correct flattened format
|
||||
// Just return a pointer to it
|
||||
return &response
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,30 +18,30 @@ import (
|
|||
func TestReadSeedFile_LocalFile(t *testing.T) {
|
||||
// Create a temporary seed file in extension wrapper format
|
||||
tempFile := "/tmp/test_seed.json"
|
||||
seedData := []apiv0.ServerRecord{
|
||||
seedData := []apiv0.ServerJSON{
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "com.example/test-server-1",
|
||||
Description: "Test server 1",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/test/repo1",
|
||||
Source: "github",
|
||||
ID: "123",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
},
|
||||
Name: "com.example/test-server-1",
|
||||
Description: "Test server 1",
|
||||
Repository: model.Repository{
|
||||
URL: "https://github.com/test/repo1",
|
||||
Source: "github",
|
||||
ID: "123",
|
||||
},
|
||||
VersionDetail: model.VersionDetail{
|
||||
Version: "1.0.0",
|
||||
},
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "test-id-1",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "test-id-1",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -66,27 +66,27 @@ func TestReadSeedFile_LocalFile(t *testing.T) {
|
|||
result, err := database.ReadSeedFile(context.Background(), tempFile)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, result, 1)
|
||||
assert.Equal(t, "com.example/test-server-1", result[0].Server.Name)
|
||||
assert.Equal(t, "com.example/test-server-1", result[0].Name)
|
||||
}
|
||||
|
||||
func TestReadSeedFile_DirectHTTPURL(t *testing.T) {
|
||||
// Create a test HTTP server that serves seed JSON directly in extension wrapper format
|
||||
seedData := []apiv0.ServerRecord{
|
||||
seedData := []apiv0.ServerJSON{
|
||||
{
|
||||
Server: model.ServerJSON{
|
||||
Name: "com.example/test-server-1",
|
||||
Description: "Test server 1",
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
},
|
||||
Name: "com.example/test-server-1",
|
||||
Description: "Test server 1",
|
||||
Remotes: []model.Remote{
|
||||
{
|
||||
URL: "https://example.com/remote",
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "test-id-1",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "test-id-1",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -103,53 +103,53 @@ func TestReadSeedFile_DirectHTTPURL(t *testing.T) {
|
|||
result, err := database.ReadSeedFile(context.Background(), server.URL+"/seed.json")
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, result, 1)
|
||||
assert.Equal(t, "com.example/test-server-1", result[0].Server.Name)
|
||||
assert.Equal(t, "com.example/test-server-1", result[0].Name)
|
||||
}
|
||||
|
||||
func TestReadSeedFile_RegistryURL(t *testing.T) {
|
||||
// Create mock registry responses
|
||||
server1 := apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "Test Server 1",
|
||||
Description: "First test server",
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: "npm",
|
||||
RegistryBaseURL: "https://registry.npmjs.org",
|
||||
Identifier: "test-package-1",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
server1 := apiv0.ServerJSON{
|
||||
Name: "Test Server 1",
|
||||
Description: "First test server",
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: "npm",
|
||||
RegistryBaseURL: "https://registry.npmjs.org",
|
||||
Identifier: "test-package-1",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "server-1",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "server-1",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
}
|
||||
server2 := apiv0.ServerRecord{
|
||||
Server: model.ServerJSON{
|
||||
Name: "Test Server 2",
|
||||
Description: "Second test server",
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: "npm",
|
||||
RegistryBaseURL: "https://registry.npmjs.org",
|
||||
Identifier: "test-package-2",
|
||||
Version: "2.0.0",
|
||||
},
|
||||
server2 := apiv0.ServerJSON{
|
||||
Name: "Test Server 2",
|
||||
Description: "Second test server",
|
||||
Packages: []model.Package{
|
||||
{
|
||||
RegistryType: "npm",
|
||||
RegistryBaseURL: "https://registry.npmjs.org",
|
||||
Identifier: "test-package-2",
|
||||
Version: "2.0.0",
|
||||
},
|
||||
},
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: "server-2",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
Meta: &apiv0.ServerMeta{
|
||||
IOModelContextProtocolRegistry: &apiv0.RegistryExtensions{
|
||||
ID: "server-2",
|
||||
PublishedAt: time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC),
|
||||
IsLatest: true,
|
||||
ReleaseDate: "2023-01-01T00:00:00Z",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
serverDetail1 := model.ServerJSON{
|
||||
serverDetail1 := apiv0.ServerJSON{
|
||||
Name: "Test Server 1",
|
||||
Description: "First test server",
|
||||
Packages: []model.Package{
|
||||
|
|
@ -161,7 +161,7 @@ func TestReadSeedFile_RegistryURL(t *testing.T) {
|
|||
},
|
||||
},
|
||||
}
|
||||
serverDetail2 := model.ServerJSON{
|
||||
serverDetail2 := apiv0.ServerJSON{
|
||||
Name: "Test Server 2",
|
||||
Description: "Second test server",
|
||||
Packages: []model.Package{
|
||||
|
|
@ -187,8 +187,8 @@ func TestReadSeedFile_RegistryURL(t *testing.T) {
|
|||
}
|
||||
|
||||
type PaginatedResponse struct {
|
||||
Servers []apiv0.ServerRecord `json:"servers"`
|
||||
Metadata *Metadata `json:"metadata,omitempty"`
|
||||
Servers []apiv0.ServerJSON `json:"servers"`
|
||||
Metadata *Metadata `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
var response PaginatedResponse
|
||||
|
|
@ -196,7 +196,7 @@ func TestReadSeedFile_RegistryURL(t *testing.T) {
|
|||
case "":
|
||||
// First page
|
||||
response = PaginatedResponse{
|
||||
Servers: []apiv0.ServerRecord{server1},
|
||||
Servers: []apiv0.ServerJSON{server1},
|
||||
Metadata: &Metadata{
|
||||
NextCursor: "next-cursor-1",
|
||||
Count: 1,
|
||||
|
|
@ -205,7 +205,7 @@ func TestReadSeedFile_RegistryURL(t *testing.T) {
|
|||
case "next-cursor-1":
|
||||
// Second page
|
||||
response = PaginatedResponse{
|
||||
Servers: []apiv0.ServerRecord{server2},
|
||||
Servers: []apiv0.ServerJSON{server2},
|
||||
Metadata: &Metadata{
|
||||
Count: 1,
|
||||
// No NextCursor means end of pagination
|
||||
|
|
@ -214,7 +214,7 @@ func TestReadSeedFile_RegistryURL(t *testing.T) {
|
|||
default:
|
||||
// No more pages
|
||||
response = PaginatedResponse{
|
||||
Servers: []apiv0.ServerRecord{},
|
||||
Servers: []apiv0.ServerJSON{},
|
||||
Metadata: &Metadata{},
|
||||
}
|
||||
}
|
||||
|
|
@ -249,20 +249,20 @@ func TestReadSeedFile_RegistryURL(t *testing.T) {
|
|||
assert.Len(t, result, 2)
|
||||
|
||||
// Verify the servers were imported correctly
|
||||
assert.Equal(t, "Test Server 1", result[0].Server.Name)
|
||||
assert.Equal(t, "Test Server 2", result[1].Server.Name)
|
||||
assert.Equal(t, "Test Server 1", result[0].Name)
|
||||
assert.Equal(t, "Test Server 2", result[1].Name)
|
||||
|
||||
// Verify packages were imported with new schema
|
||||
assert.Len(t, result[0].Server.Packages, 1)
|
||||
assert.Equal(t, "npm", result[0].Server.Packages[0].RegistryType)
|
||||
assert.Equal(t, "https://registry.npmjs.org", result[0].Server.Packages[0].RegistryBaseURL)
|
||||
assert.Equal(t, "test-package-1", result[0].Server.Packages[0].Identifier)
|
||||
assert.Len(t, result[1].Server.Packages, 1)
|
||||
assert.Equal(t, "npm", result[1].Server.Packages[0].RegistryType)
|
||||
assert.Equal(t, "https://registry.npmjs.org", result[1].Server.Packages[0].RegistryBaseURL)
|
||||
assert.Equal(t, "test-package-2", result[1].Server.Packages[0].Identifier)
|
||||
assert.Len(t, result[0].Packages, 1)
|
||||
assert.Equal(t, "npm", result[0].Packages[0].RegistryType)
|
||||
assert.Equal(t, "https://registry.npmjs.org", result[0].Packages[0].RegistryBaseURL)
|
||||
assert.Equal(t, "test-package-1", result[0].Packages[0].Identifier)
|
||||
assert.Len(t, result[1].Packages, 1)
|
||||
assert.Equal(t, "npm", result[1].Packages[0].RegistryType)
|
||||
assert.Equal(t, "https://registry.npmjs.org", result[1].Packages[0].RegistryBaseURL)
|
||||
assert.Equal(t, "test-package-2", result[1].Packages[0].Identifier)
|
||||
|
||||
// Verify metadata was extracted
|
||||
assert.Equal(t, "server-1", result[0].XIOModelContextProtocolRegistry.ID)
|
||||
assert.Equal(t, "server-2", result[1].XIOModelContextProtocolRegistry.ID)
|
||||
assert.Equal(t, "server-1", result[0].Meta.IOModelContextProtocolRegistry.ID)
|
||||
assert.Equal(t, "server-2", result[1].Meta.IOModelContextProtocolRegistry.ID)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,47 +8,49 @@ import (
|
|||
"time"
|
||||
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// MemoryDB is an in-memory implementation of the Database interface
|
||||
type MemoryDB struct {
|
||||
entries map[string]*apiv0.ServerRecord // maps registry metadata ID to ServerRecord
|
||||
entries map[string]*apiv0.ServerJSON // maps registry metadata ID to ServerJSON
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewMemoryDB creates a new instance of the in-memory database
|
||||
func NewMemoryDB(e map[string]*model.ServerJSON) *MemoryDB {
|
||||
// Convert ServerJSON entries to ServerRecord entries
|
||||
serverRecords := make(map[string]*apiv0.ServerRecord)
|
||||
func NewMemoryDB(e map[string]*apiv0.ServerJSON) *MemoryDB {
|
||||
// Convert input ServerJSON entries to have proper metadata
|
||||
serverRecords := make(map[string]*apiv0.ServerJSON)
|
||||
for registryID, serverDetail := range e {
|
||||
// Create registry metadata
|
||||
// Create a copy and add registry metadata
|
||||
now := time.Now()
|
||||
record := &apiv0.ServerRecord{
|
||||
Server: *serverDetail,
|
||||
XIOModelContextProtocolRegistry: apiv0.RegistryExtensions{
|
||||
ID: registryID,
|
||||
PublishedAt: now,
|
||||
UpdatedAt: now,
|
||||
IsLatest: true,
|
||||
ReleaseDate: now.Format(time.RFC3339),
|
||||
},
|
||||
XPublisher: make(map[string]interface{}),
|
||||
server := *serverDetail // Copy the server
|
||||
if server.Meta == nil {
|
||||
server.Meta = &apiv0.ServerMeta{}
|
||||
}
|
||||
serverRecords[registryID] = record
|
||||
server.Meta.IOModelContextProtocolRegistry = &apiv0.RegistryExtensions{
|
||||
ID: registryID,
|
||||
PublishedAt: now,
|
||||
UpdatedAt: now,
|
||||
IsLatest: true,
|
||||
ReleaseDate: now.Format(time.RFC3339),
|
||||
}
|
||||
if server.Meta.Publisher == nil {
|
||||
server.Meta.Publisher = make(map[string]interface{})
|
||||
}
|
||||
serverRecords[registryID] = &server
|
||||
}
|
||||
return &MemoryDB{
|
||||
entries: serverRecords,
|
||||
}
|
||||
}
|
||||
|
||||
//nolint:cyclop // Complexity from filtering logic is acceptable for memory implementation
|
||||
//nolint:cyclop,gocyclo,gocognit // Complexity from filtering logic is acceptable for memory implementation
|
||||
func (db *MemoryDB) List(
|
||||
ctx context.Context,
|
||||
filter map[string]any,
|
||||
cursor string,
|
||||
limit int,
|
||||
) ([]*apiv0.ServerRecord, string, error) {
|
||||
) ([]*apiv0.ServerJSON, string, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, "", ctx.Err()
|
||||
}
|
||||
|
|
@ -61,15 +63,15 @@ func (db *MemoryDB) List(
|
|||
defer db.mu.RUnlock()
|
||||
|
||||
// Convert all entries to a slice for pagination, filter by is_latest
|
||||
var allEntries []*apiv0.ServerRecord
|
||||
var allEntries []*apiv0.ServerJSON
|
||||
for _, entry := range db.entries {
|
||||
if entry.XIOModelContextProtocolRegistry.IsLatest {
|
||||
if entry.Meta != nil && entry.Meta.IOModelContextProtocolRegistry != nil && entry.Meta.IOModelContextProtocolRegistry.IsLatest {
|
||||
allEntries = append(allEntries, entry)
|
||||
}
|
||||
}
|
||||
|
||||
// Simple filtering implementation
|
||||
var filteredEntries []*apiv0.ServerRecord
|
||||
var filteredEntries []*apiv0.ServerJSON
|
||||
for _, entry := range allEntries {
|
||||
include := true
|
||||
|
||||
|
|
@ -77,21 +79,21 @@ func (db *MemoryDB) List(
|
|||
for key, value := range filter {
|
||||
switch key {
|
||||
case "name":
|
||||
if entry.Server.Name != value.(string) {
|
||||
if entry.Name != value.(string) {
|
||||
include = false
|
||||
}
|
||||
case "version":
|
||||
if entry.Server.VersionDetail.Version != value.(string) {
|
||||
if entry.VersionDetail.Version != value.(string) {
|
||||
include = false
|
||||
}
|
||||
case "status":
|
||||
if string(entry.Server.Status) != value.(string) {
|
||||
if string(entry.Status) != value.(string) {
|
||||
include = false
|
||||
}
|
||||
case "remote_url":
|
||||
found := false
|
||||
remoteURL := value.(string)
|
||||
for _, remote := range entry.Server.Remotes {
|
||||
for _, remote := range entry.Remotes {
|
||||
if remote.URL == remoteURL {
|
||||
found = true
|
||||
break
|
||||
|
|
@ -110,14 +112,23 @@ func (db *MemoryDB) List(
|
|||
|
||||
// Sort filteredEntries by registry metadata ID for consistent pagination
|
||||
sort.Slice(filteredEntries, func(i, j int) bool {
|
||||
return filteredEntries[i].XIOModelContextProtocolRegistry.ID < filteredEntries[j].XIOModelContextProtocolRegistry.ID
|
||||
iID := ""
|
||||
jID := ""
|
||||
if filteredEntries[i].Meta != nil && filteredEntries[i].Meta.IOModelContextProtocolRegistry != nil {
|
||||
iID = filteredEntries[i].Meta.IOModelContextProtocolRegistry.ID
|
||||
}
|
||||
if filteredEntries[j].Meta != nil && filteredEntries[j].Meta.IOModelContextProtocolRegistry != nil {
|
||||
jID = filteredEntries[j].Meta.IOModelContextProtocolRegistry.ID
|
||||
}
|
||||
return iID < jID
|
||||
})
|
||||
|
||||
// Find starting point for cursor-based pagination using registry metadata ID
|
||||
startIdx := 0
|
||||
if cursor != "" {
|
||||
for i, entry := range filteredEntries {
|
||||
if entry.XIOModelContextProtocolRegistry.ID == cursor {
|
||||
if entry.Meta != nil && entry.Meta.IOModelContextProtocolRegistry != nil &&
|
||||
entry.Meta.IOModelContextProtocolRegistry.ID == cursor {
|
||||
startIdx = i + 1 // Start after the cursor
|
||||
break
|
||||
}
|
||||
|
|
@ -127,24 +138,27 @@ func (db *MemoryDB) List(
|
|||
// Apply pagination
|
||||
endIdx := min(startIdx+limit, len(filteredEntries))
|
||||
|
||||
var result []*apiv0.ServerRecord
|
||||
var result []*apiv0.ServerJSON
|
||||
if startIdx < len(filteredEntries) {
|
||||
result = filteredEntries[startIdx:endIdx]
|
||||
} else {
|
||||
result = []*apiv0.ServerRecord{}
|
||||
result = []*apiv0.ServerJSON{}
|
||||
}
|
||||
|
||||
// Determine next cursor using registry metadata ID
|
||||
nextCursor := ""
|
||||
if endIdx < len(filteredEntries) {
|
||||
nextCursor = filteredEntries[endIdx-1].XIOModelContextProtocolRegistry.ID
|
||||
if endIdx < len(filteredEntries) && len(result) > 0 {
|
||||
lastEntry := result[len(result)-1]
|
||||
if lastEntry.Meta != nil && lastEntry.Meta.IOModelContextProtocolRegistry != nil {
|
||||
nextCursor = lastEntry.Meta.IOModelContextProtocolRegistry.ID
|
||||
}
|
||||
}
|
||||
|
||||
return result, nextCursor, nil
|
||||
}
|
||||
|
||||
// GetByID retrieves a single ServerRecord by its registry metadata ID
|
||||
func (db *MemoryDB) GetByID(ctx context.Context, id string) (*apiv0.ServerRecord, error) {
|
||||
func (db *MemoryDB) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
|
@ -163,7 +177,7 @@ func (db *MemoryDB) GetByID(ctx context.Context, id string) (*apiv0.ServerRecord
|
|||
}
|
||||
|
||||
// Publish adds a new server to the database with separated server.json and extensions
|
||||
func (db *MemoryDB) Publish(ctx context.Context, serverDetail model.ServerJSON, publisherExtensions map[string]interface{}, registryMetadata apiv0.RegistryExtensions) (*apiv0.ServerRecord, error) {
|
||||
func (db *MemoryDB) Publish(ctx context.Context, serverDetail apiv0.ServerJSON, publisherExtensions map[string]interface{}, registryMetadata apiv0.RegistryExtensions) (*apiv0.ServerJSON, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
|
@ -187,17 +201,26 @@ func (db *MemoryDB) Publish(ctx context.Context, serverDetail model.ServerJSON,
|
|||
return nil, ErrInvalidInput
|
||||
}
|
||||
|
||||
// Create server record
|
||||
record := &apiv0.ServerRecord{
|
||||
Server: serverDetail,
|
||||
XIOModelContextProtocolRegistry: registryMetadata,
|
||||
XPublisher: publisherExtensions,
|
||||
// Create server record with metadata
|
||||
record := serverDetail // Copy the input
|
||||
|
||||
// Initialize meta if not present
|
||||
if record.Meta == nil {
|
||||
record.Meta = &apiv0.ServerMeta{}
|
||||
}
|
||||
|
||||
// Set registry metadata
|
||||
record.Meta.IOModelContextProtocolRegistry = ®istryMetadata
|
||||
|
||||
// Set publisher extensions if provided
|
||||
if len(publisherExtensions) > 0 {
|
||||
record.Meta.Publisher = publisherExtensions
|
||||
}
|
||||
|
||||
// Store the record using registry metadata ID
|
||||
db.entries[registryMetadata.ID] = record
|
||||
db.entries[registryMetadata.ID] = &record
|
||||
|
||||
return record, nil
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// ImportSeed imports initial data from a seed file into memory database
|
||||
|
|
@ -220,7 +243,9 @@ func (db *MemoryDB) ImportSeed(ctx context.Context, seedFilePath string) error {
|
|||
// Import each server
|
||||
for _, record := range seedData {
|
||||
// Use the registry metadata ID as the map key
|
||||
db.entries[record.XIOModelContextProtocolRegistry.ID] = record
|
||||
if record.Meta != nil && record.Meta.IOModelContextProtocolRegistry != nil {
|
||||
db.entries[record.Meta.IOModelContextProtocolRegistry.ID] = record
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -236,8 +261,10 @@ func (db *MemoryDB) UpdateLatestFlag(ctx context.Context, id string, isLatest bo
|
|||
defer db.mu.Unlock()
|
||||
|
||||
if entry, exists := db.entries[id]; exists {
|
||||
entry.XIOModelContextProtocolRegistry.IsLatest = isLatest
|
||||
entry.XIOModelContextProtocolRegistry.UpdatedAt = time.Now()
|
||||
if entry.Meta != nil && entry.Meta.IOModelContextProtocolRegistry != nil {
|
||||
entry.Meta.IOModelContextProtocolRegistry.IsLatest = isLatest
|
||||
entry.Meta.IOModelContextProtocolRegistry.UpdatedAt = time.Now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
@ -245,7 +272,7 @@ func (db *MemoryDB) UpdateLatestFlag(ctx context.Context, id string, isLatest bo
|
|||
}
|
||||
|
||||
// UpdateServer updates an existing server record with new server details
|
||||
func (db *MemoryDB) UpdateServer(ctx context.Context, id string, serverDetail model.ServerJSON, publisherExtensions map[string]interface{}) (*apiv0.ServerRecord, error) {
|
||||
func (db *MemoryDB) UpdateServer(ctx context.Context, id string, serverDetail apiv0.ServerJSON, publisherExtensions map[string]interface{}) (*apiv0.ServerJSON, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
|
@ -258,10 +285,19 @@ func (db *MemoryDB) UpdateServer(ctx context.Context, id string, serverDetail mo
|
|||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// Update the server details
|
||||
entry.Server = serverDetail
|
||||
entry.XPublisher = publisherExtensions
|
||||
entry.XIOModelContextProtocolRegistry.UpdatedAt = time.Now()
|
||||
// Update the server details by copying fields from serverDetail
|
||||
*entry = serverDetail
|
||||
|
||||
// Ensure meta exists and update it
|
||||
if entry.Meta == nil {
|
||||
entry.Meta = &apiv0.ServerMeta{}
|
||||
}
|
||||
if entry.Meta.IOModelContextProtocolRegistry != nil {
|
||||
entry.Meta.IOModelContextProtocolRegistry.UpdatedAt = time.Now()
|
||||
}
|
||||
if len(publisherExtensions) > 0 {
|
||||
entry.Meta.Publisher = publisherExtensions
|
||||
}
|
||||
|
||||
// Return the updated record
|
||||
return entry, nil
|
||||
|
|
|
|||
24
internal/database/migrations/003_simplify_to_key_value.sql
Normal file
24
internal/database/migrations/003_simplify_to_key_value.sql
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
-- Simplify database to simple key-value table with id, value
|
||||
-- This migration drops all existing data and creates a clean simple structure
|
||||
|
||||
-- Drop old tables and functions
|
||||
DROP TRIGGER IF EXISTS update_server_extensions_on_server_update ON servers;
|
||||
DROP FUNCTION IF EXISTS update_server_extensions_updated_at();
|
||||
DROP TRIGGER IF EXISTS update_servers_updated_at ON servers;
|
||||
DROP FUNCTION IF EXISTS update_updated_at_column();
|
||||
|
||||
DROP TABLE IF EXISTS server_extensions;
|
||||
DROP TABLE IF EXISTS servers;
|
||||
|
||||
-- Create new simple servers table
|
||||
CREATE TABLE servers (
|
||||
id VARCHAR(255) PRIMARY KEY, -- Use registry metadata ID as primary key
|
||||
value JSONB NOT NULL -- Complete ServerJSON as JSONB
|
||||
);
|
||||
|
||||
-- Create essential indexes for performance
|
||||
CREATE INDEX idx_servers_id ON servers (id);
|
||||
CREATE INDEX idx_servers_name_latest ON servers ((value->>'name'), (value->'_meta'->'io.modelcontextprotocol.registry'->>'is_latest'))
|
||||
WHERE (value->'_meta'->'io.modelcontextprotocol.registry'->>'is_latest')::boolean = true;
|
||||
CREATE INDEX idx_servers_updated_at ON servers ((value->'_meta'->'io.modelcontextprotocol.registry'->>'updated_at'));
|
||||
CREATE INDEX idx_servers_remotes ON servers USING GIN((value->'remotes'));
|
||||
|
|
@ -6,12 +6,12 @@ import (
|
|||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// PostgreSQL is an implementation of the Database interface using PostgreSQL
|
||||
|
|
@ -42,13 +42,13 @@ func NewPostgreSQL(ctx context.Context, connectionURI string) (*PostgreSQL, erro
|
|||
}, nil
|
||||
}
|
||||
|
||||
// List retrieves ServerRecord entries with optional filtering and pagination
|
||||
// List retrieves ServerJSON entries with optional filtering and pagination
|
||||
func (db *PostgreSQL) List(
|
||||
ctx context.Context,
|
||||
filter map[string]any,
|
||||
cursor string,
|
||||
limit int,
|
||||
) ([]*apiv0.ServerRecord, string, error) {
|
||||
) ([]*apiv0.ServerJSON, string, error) {
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
|
|
@ -57,28 +57,29 @@ func (db *PostgreSQL) List(
|
|||
return nil, "", ctx.Err()
|
||||
}
|
||||
|
||||
// Build WHERE clause for server_extensions filtering
|
||||
whereClause := "WHERE se.is_latest = true"
|
||||
// Build WHERE clause for filtering - always filter by is_latest = true by default
|
||||
var whereConditions []string
|
||||
whereConditions = append(whereConditions, "(value->'_meta'->'io.modelcontextprotocol.registry'->>'is_latest')::boolean = true")
|
||||
args := []any{}
|
||||
argIndex := 1
|
||||
|
||||
// Add filters
|
||||
// Add filters using JSON operators
|
||||
for k, v := range filter {
|
||||
switch k {
|
||||
case "name":
|
||||
whereClause += fmt.Sprintf(" AND s.name = $%d", argIndex)
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("value->>'name' = $%d", argIndex))
|
||||
args = append(args, v)
|
||||
argIndex++
|
||||
case "version":
|
||||
whereClause += fmt.Sprintf(" AND s.version = $%d", argIndex)
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("value->'version_detail'->>'version' = $%d", argIndex))
|
||||
args = append(args, v)
|
||||
argIndex++
|
||||
case "status":
|
||||
whereClause += fmt.Sprintf(" AND s.status = $%d", argIndex)
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("value->>'status' = $%d", argIndex))
|
||||
args = append(args, v)
|
||||
argIndex++
|
||||
case "remote_url":
|
||||
whereClause += fmt.Sprintf(" AND EXISTS (SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(s.remotes) = 'array' THEN s.remotes ELSE '[]'::jsonb END) AS remote WHERE remote->>'url' = $%d)", argIndex)
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("EXISTS (SELECT 1 FROM jsonb_array_elements(value->'remotes') AS remote WHERE remote->>'url' = $%d)", argIndex))
|
||||
args = append(args, v)
|
||||
argIndex++
|
||||
}
|
||||
|
|
@ -89,68 +90,49 @@ func (db *PostgreSQL) List(
|
|||
if _, err := uuid.Parse(cursor); err != nil {
|
||||
return nil, "", fmt.Errorf("invalid cursor format: %w", err)
|
||||
}
|
||||
whereClause += fmt.Sprintf(" AND se.id > $%d", argIndex)
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("(value->'_meta'->'io.modelcontextprotocol.registry'->>'id') > $%d", argIndex))
|
||||
args = append(args, cursor)
|
||||
argIndex++
|
||||
}
|
||||
|
||||
// Build JOIN query between servers and server_extensions
|
||||
// Build the WHERE clause
|
||||
whereClause := ""
|
||||
if len(whereConditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
|
||||
}
|
||||
|
||||
// Simple query on servers table
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
s.name, s.description, s.status, s.repository, s.version, s.packages, s.remotes,
|
||||
se.id, se.published_at, se.updated_at, se.is_latest, se.release_date, se.publisher_extensions
|
||||
FROM servers s
|
||||
JOIN server_extensions se ON s.id = se.server_id
|
||||
SELECT value
|
||||
FROM servers
|
||||
%s
|
||||
ORDER BY se.id
|
||||
ORDER BY (value->'_meta'->'io.modelcontextprotocol.registry'->>'id')
|
||||
LIMIT $%d
|
||||
`, whereClause, argIndex)
|
||||
args = append(args, limit)
|
||||
|
||||
rows, err := db.conn.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to query servers with extensions: %w", err)
|
||||
return nil, "", fmt.Errorf("failed to query servers: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var results []*apiv0.ServerRecord
|
||||
var results []*apiv0.ServerJSON
|
||||
for rows.Next() {
|
||||
var record apiv0.ServerRecord
|
||||
var repositoryJSON, packagesJSON, remotesJSON, publisherExtensionsJSON []byte
|
||||
var publishedAt, updatedAt, releaseDate time.Time
|
||||
var valueJSON []byte
|
||||
|
||||
err := rows.Scan(
|
||||
// Server fields
|
||||
&record.Server.Name,
|
||||
&record.Server.Description,
|
||||
&record.Server.Status,
|
||||
&repositoryJSON,
|
||||
&record.Server.VersionDetail.Version,
|
||||
&packagesJSON,
|
||||
&remotesJSON,
|
||||
// Registry metadata fields
|
||||
&record.XIOModelContextProtocolRegistry.ID,
|
||||
&publishedAt,
|
||||
&updatedAt,
|
||||
&record.XIOModelContextProtocolRegistry.IsLatest,
|
||||
&releaseDate,
|
||||
&publisherExtensionsJSON,
|
||||
)
|
||||
err := rows.Scan(&valueJSON)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to scan server record row: %w", err)
|
||||
return nil, "", fmt.Errorf("failed to scan server row: %w", err)
|
||||
}
|
||||
|
||||
// Parse JSON fields
|
||||
if err := parseJSONFields(&record, repositoryJSON, packagesJSON, remotesJSON, publisherExtensionsJSON); err != nil {
|
||||
return nil, "", 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)
|
||||
}
|
||||
|
||||
// Set registry metadata timestamps
|
||||
record.XIOModelContextProtocolRegistry.PublishedAt = publishedAt
|
||||
record.XIOModelContextProtocolRegistry.UpdatedAt = updatedAt
|
||||
record.XIOModelContextProtocolRegistry.ReleaseDate = releaseDate.Format(time.RFC3339)
|
||||
|
||||
results = append(results, &record)
|
||||
results = append(results, &serverJSON)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
|
|
@ -160,213 +142,87 @@ func (db *PostgreSQL) List(
|
|||
// Determine next cursor using registry metadata ID
|
||||
nextCursor := ""
|
||||
if len(results) > 0 && len(results) >= limit {
|
||||
nextCursor = results[len(results)-1].XIOModelContextProtocolRegistry.ID
|
||||
lastResult := results[len(results)-1]
|
||||
if lastResult.Meta != nil && lastResult.Meta.IOModelContextProtocolRegistry != nil {
|
||||
nextCursor = lastResult.Meta.IOModelContextProtocolRegistry.ID
|
||||
}
|
||||
}
|
||||
|
||||
return results, nextCursor, nil
|
||||
}
|
||||
|
||||
// parseJSONFields parses JSON fields for a server record
|
||||
func parseJSONFields(record *apiv0.ServerRecord, repositoryJSON, packagesJSON, remotesJSON, publisherExtensionsJSON []byte) error {
|
||||
if len(repositoryJSON) > 0 {
|
||||
if err := json.Unmarshal(repositoryJSON, &record.Server.Repository); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal repository: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(packagesJSON) > 0 {
|
||||
if err := json.Unmarshal(packagesJSON, &record.Server.Packages); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal packages: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(remotesJSON) > 0 {
|
||||
if err := json.Unmarshal(remotesJSON, &record.Server.Remotes); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal remotes: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(publisherExtensionsJSON) > 0 {
|
||||
if err := json.Unmarshal(publisherExtensionsJSON, &record.XPublisher); err != nil {
|
||||
return fmt.Errorf("failed to unmarshal publisher extensions: %w", err)
|
||||
}
|
||||
} else {
|
||||
record.XPublisher = make(map[string]interface{})
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetByID retrieves a single ServerRecord by its registry metadata ID
|
||||
func (db *PostgreSQL) GetByID(ctx context.Context, id string) (*apiv0.ServerRecord, error) {
|
||||
// GetByID retrieves a single ServerJSON by its registry metadata ID
|
||||
func (db *PostgreSQL) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT
|
||||
s.name, s.description, s.status, s.repository, s.version, s.packages, s.remotes,
|
||||
se.id, se.published_at, se.updated_at, se.is_latest, se.release_date, se.publisher_extensions
|
||||
FROM servers s
|
||||
JOIN server_extensions se ON s.id = se.server_id
|
||||
WHERE se.id = $1
|
||||
SELECT value
|
||||
FROM servers
|
||||
WHERE (value->'_meta'->'io.modelcontextprotocol.registry'->>'id') = $1
|
||||
`
|
||||
|
||||
var record apiv0.ServerRecord
|
||||
var repositoryJSON, packagesJSON, remotesJSON, publisherExtensionsJSON []byte
|
||||
var publishedAt, updatedAt, releaseDate time.Time
|
||||
var valueJSON []byte
|
||||
|
||||
err := db.conn.QueryRow(ctx, query, id).Scan(
|
||||
// Server fields
|
||||
&record.Server.Name,
|
||||
&record.Server.Description,
|
||||
&record.Server.Status,
|
||||
&repositoryJSON,
|
||||
&record.Server.VersionDetail.Version,
|
||||
&packagesJSON,
|
||||
&remotesJSON,
|
||||
// Registry metadata fields
|
||||
&record.XIOModelContextProtocolRegistry.ID,
|
||||
&publishedAt,
|
||||
&updatedAt,
|
||||
&record.XIOModelContextProtocolRegistry.IsLatest,
|
||||
&releaseDate,
|
||||
&publisherExtensionsJSON,
|
||||
)
|
||||
err := db.conn.QueryRow(ctx, query, id).Scan(&valueJSON)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get server record by ID: %w", err)
|
||||
return nil, fmt.Errorf("failed to get server by ID: %w", err)
|
||||
}
|
||||
|
||||
// Parse JSON fields
|
||||
if len(repositoryJSON) > 0 {
|
||||
if err := json.Unmarshal(repositoryJSON, &record.Server.Repository); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal repository: %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)
|
||||
}
|
||||
|
||||
if len(packagesJSON) > 0 {
|
||||
if err := json.Unmarshal(packagesJSON, &record.Server.Packages); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal packages: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(remotesJSON) > 0 {
|
||||
if err := json.Unmarshal(remotesJSON, &record.Server.Remotes); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal remotes: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse publisher extensions
|
||||
if len(publisherExtensionsJSON) > 0 {
|
||||
if err := json.Unmarshal(publisherExtensionsJSON, &record.XPublisher); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal publisher extensions: %w", err)
|
||||
}
|
||||
} else {
|
||||
record.XPublisher = make(map[string]interface{})
|
||||
}
|
||||
|
||||
// Set registry metadata timestamps
|
||||
record.XIOModelContextProtocolRegistry.PublishedAt = publishedAt
|
||||
record.XIOModelContextProtocolRegistry.UpdatedAt = updatedAt
|
||||
record.XIOModelContextProtocolRegistry.ReleaseDate = releaseDate.Format(time.RFC3339)
|
||||
|
||||
return &record, nil
|
||||
return &serverJSON, nil
|
||||
}
|
||||
|
||||
// Publish adds a new server to the database with separated server.json and extensions
|
||||
func (db *PostgreSQL) Publish(ctx context.Context, serverDetail model.ServerJSON, publisherExtensions map[string]interface{}, registryMetadata apiv0.RegistryExtensions) (*apiv0.ServerRecord, error) {
|
||||
// Publish adds a new server to the simple servers table
|
||||
func (db *PostgreSQL) Publish(ctx context.Context, serverDetail apiv0.ServerJSON, publisherExtensions map[string]interface{}, registryMetadata apiv0.RegistryExtensions) (*apiv0.ServerJSON, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
tx, err := db.conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := tx.Rollback(ctx); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
||||
log.Printf("Failed to rollback transaction: %v", err)
|
||||
}
|
||||
}()
|
||||
// Create complete server with metadata
|
||||
server := serverDetail // Copy the input
|
||||
|
||||
// Prepare JSON data for server table
|
||||
repositoryJSON, err := json.Marshal(serverDetail.Repository)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal repository: %w", err)
|
||||
// Initialize meta if not present
|
||||
if server.Meta == nil {
|
||||
server.Meta = &apiv0.ServerMeta{}
|
||||
}
|
||||
|
||||
packagesJSON, err := json.Marshal(serverDetail.Packages)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal packages: %w", err)
|
||||
// Set registry metadata
|
||||
server.Meta.IOModelContextProtocolRegistry = ®istryMetadata
|
||||
|
||||
// Set publisher extensions if provided
|
||||
if len(publisherExtensions) > 0 {
|
||||
server.Meta.Publisher = publisherExtensions
|
||||
}
|
||||
|
||||
remotesJSON, err := json.Marshal(serverDetail.Remotes)
|
||||
// Marshal the complete server to JSONB
|
||||
valueJSON, err := json.Marshal(server)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal remotes: %w", err)
|
||||
return nil, fmt.Errorf("failed to marshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
publisherExtensionsJSON, err := json.Marshal(publisherExtensions)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal publisher extensions: %w", err)
|
||||
}
|
||||
|
||||
// Use the same ID for both server and server_extensions records (1:1 relationship)
|
||||
serverID := registryMetadata.ID
|
||||
|
||||
// Insert new server record
|
||||
insertServerQuery := `
|
||||
INSERT INTO servers (id, name, description, status, repository, version, packages, remotes)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
// Insert into simple servers table
|
||||
query := `
|
||||
INSERT INTO servers (id, value)
|
||||
VALUES ($1, $2)
|
||||
`
|
||||
_, err = tx.Exec(ctx, insertServerQuery,
|
||||
serverID,
|
||||
serverDetail.Name,
|
||||
serverDetail.Description,
|
||||
serverDetail.Status,
|
||||
repositoryJSON,
|
||||
serverDetail.VersionDetail.Version,
|
||||
packagesJSON,
|
||||
remotesJSON,
|
||||
)
|
||||
|
||||
_, err = db.conn.Exec(ctx, query, registryMetadata.ID, valueJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to insert server: %w", err)
|
||||
}
|
||||
|
||||
// Insert server extensions record
|
||||
insertExtensionsQuery := `
|
||||
INSERT INTO server_extensions (id, server_id, published_at, updated_at, is_latest, release_date, publisher_extensions)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
`
|
||||
_, err = tx.Exec(ctx, insertExtensionsQuery,
|
||||
registryMetadata.ID,
|
||||
serverID,
|
||||
registryMetadata.PublishedAt,
|
||||
registryMetadata.UpdatedAt,
|
||||
registryMetadata.IsLatest,
|
||||
registryMetadata.PublishedAt, // release_date
|
||||
publisherExtensionsJSON,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to insert server extensions: %w", err)
|
||||
}
|
||||
|
||||
// Commit transaction
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, fmt.Errorf("failed to commit transaction: %w", err)
|
||||
}
|
||||
|
||||
// Create and return the ServerRecord
|
||||
record := &apiv0.ServerRecord{
|
||||
Server: serverDetail,
|
||||
XIOModelContextProtocolRegistry: registryMetadata,
|
||||
XPublisher: publisherExtensions,
|
||||
}
|
||||
|
||||
return record, nil
|
||||
return &server, nil
|
||||
}
|
||||
|
||||
// ImportSeed imports initial data from a seed file into PostgreSQL
|
||||
|
|
@ -390,13 +246,24 @@ func (db *PostgreSQL) ImportSeed(ctx context.Context, seedFilePath string) error
|
|||
|
||||
// Import each server
|
||||
for _, record := range seedData {
|
||||
// Convert record to the format expected by Publish
|
||||
serverDetail := record.Server
|
||||
publisherExtensions := record.XPublisher
|
||||
// Marshal the server to JSONB
|
||||
valueJSON, err := json.Marshal(record)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal server JSON for import: %w", err)
|
||||
}
|
||||
|
||||
// Use the existing Publish logic but with specific ID from seed data
|
||||
if err := db.publishWithTransaction(ctx, tx, serverDetail, publisherExtensions, &record.XIOModelContextProtocolRegistry); err != nil {
|
||||
return fmt.Errorf("failed to import server %s: %w", serverDetail.Name, err)
|
||||
// Get registry ID from metadata
|
||||
var registryID string
|
||||
if record.Meta != nil && record.Meta.IOModelContextProtocolRegistry != nil {
|
||||
registryID = record.Meta.IOModelContextProtocolRegistry.ID
|
||||
} else {
|
||||
registryID = uuid.New().String() // Generate ID if not present
|
||||
}
|
||||
|
||||
// Insert into simple servers table
|
||||
_, err = tx.Exec(ctx, "INSERT INTO servers (id, value) VALUES ($1, $2)", registryID, valueJSON)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to import server %s: %w", record.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -408,104 +275,6 @@ func (db *PostgreSQL) ImportSeed(ctx context.Context, seedFilePath string) error
|
|||
return nil
|
||||
}
|
||||
|
||||
// publishWithTransaction handles publishing within an existing transaction, optionally with predefined metadata
|
||||
func (db *PostgreSQL) publishWithTransaction(ctx context.Context, tx pgx.Tx, serverDetail model.ServerJSON, publisherExtensions map[string]interface{}, existingMetadata *apiv0.RegistryExtensions) error {
|
||||
// Use the same ID for both server and server_extensions (1:1 relationship)
|
||||
var id string
|
||||
if existingMetadata != nil && existingMetadata.ID != "" {
|
||||
// Use predefined ID from seed data
|
||||
id = existingMetadata.ID
|
||||
} else {
|
||||
// This shouldn't happen as service layer should always provide an ID
|
||||
// But keeping as fallback for safety
|
||||
id = uuid.New().String()
|
||||
}
|
||||
|
||||
// Marshal packages and remotes to JSONB
|
||||
packagesJSON, err := json.Marshal(serverDetail.Packages)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal packages: %w", err)
|
||||
}
|
||||
|
||||
remotesJSON, err := json.Marshal(serverDetail.Remotes)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal remotes: %w", err)
|
||||
}
|
||||
|
||||
repositoryJSON, err := json.Marshal(serverDetail.Repository)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal repository: %w", err)
|
||||
}
|
||||
|
||||
publisherExtensionsJSON, err := json.Marshal(publisherExtensions)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal publisher extensions: %w", err)
|
||||
}
|
||||
|
||||
// Insert or update server record
|
||||
serverQuery := `
|
||||
INSERT INTO servers (id, name, description, status, repository, version, packages, remotes, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW(), NOW())
|
||||
ON CONFLICT (name, version)
|
||||
DO UPDATE SET
|
||||
description = EXCLUDED.description,
|
||||
status = EXCLUDED.status,
|
||||
repository = EXCLUDED.repository,
|
||||
packages = EXCLUDED.packages,
|
||||
remotes = EXCLUDED.remotes,
|
||||
updated_at = NOW()
|
||||
RETURNING id`
|
||||
|
||||
var returnedServerID string
|
||||
err = tx.QueryRow(ctx, serverQuery,
|
||||
id,
|
||||
serverDetail.Name,
|
||||
serverDetail.Description,
|
||||
string(serverDetail.Status),
|
||||
repositoryJSON,
|
||||
serverDetail.VersionDetail.Version,
|
||||
packagesJSON,
|
||||
remotesJSON,
|
||||
).Scan(&returnedServerID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert/update server: %w", err)
|
||||
}
|
||||
|
||||
// Insert or update server extensions
|
||||
extensionQuery := `
|
||||
INSERT INTO server_extensions (id, server_id, published_at, updated_at, is_latest, release_date, publisher_extensions)
|
||||
VALUES ($1, $2, $3, NOW(), true, $4, $5)
|
||||
ON CONFLICT (server_id)
|
||||
DO UPDATE SET
|
||||
updated_at = NOW(),
|
||||
is_latest = true,
|
||||
release_date = EXCLUDED.release_date,
|
||||
publisher_extensions = EXCLUDED.publisher_extensions`
|
||||
|
||||
var publishedAt, releaseDate string
|
||||
if existingMetadata != nil {
|
||||
publishedAt = existingMetadata.PublishedAt.Format(time.RFC3339)
|
||||
releaseDate = existingMetadata.ReleaseDate
|
||||
} else {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
publishedAt = now
|
||||
releaseDate = now
|
||||
}
|
||||
|
||||
_, err = tx.Exec(ctx, extensionQuery,
|
||||
id,
|
||||
returnedServerID,
|
||||
publishedAt,
|
||||
releaseDate,
|
||||
publisherExtensionsJSON,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert/update server extensions: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateLatestFlag updates the is_latest flag for a specific server record
|
||||
func (db *PostgreSQL) UpdateLatestFlag(ctx context.Context, id string, isLatest bool) error {
|
||||
if ctx.Err() != nil {
|
||||
|
|
@ -513,12 +282,23 @@ func (db *PostgreSQL) UpdateLatestFlag(ctx context.Context, id string, isLatest
|
|||
}
|
||||
|
||||
query := `
|
||||
UPDATE server_extensions
|
||||
SET is_latest = $1, updated_at = $2
|
||||
WHERE id = $3
|
||||
UPDATE servers
|
||||
SET value = jsonb_set(
|
||||
jsonb_set(
|
||||
value,
|
||||
'{_meta,io.modelcontextprotocol.registry,is_latest}',
|
||||
$1::jsonb
|
||||
),
|
||||
'{_meta,io.modelcontextprotocol.registry,updated_at}',
|
||||
$2::jsonb
|
||||
)
|
||||
WHERE (value->'_meta'->'io.modelcontextprotocol.registry'->>'id') = $3
|
||||
`
|
||||
|
||||
result, err := db.conn.Exec(ctx, query, isLatest, time.Now(), id)
|
||||
result, err := db.conn.Exec(ctx, query,
|
||||
fmt.Sprintf("%t", isLatest),
|
||||
fmt.Sprintf("\"%s\"", time.Now().Format(time.RFC3339)),
|
||||
id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update latest flag: %w", err)
|
||||
}
|
||||
|
|
@ -531,93 +311,57 @@ func (db *PostgreSQL) UpdateLatestFlag(ctx context.Context, id string, isLatest
|
|||
}
|
||||
|
||||
// UpdateServer updates an existing server record with new server details
|
||||
func (db *PostgreSQL) UpdateServer(ctx context.Context, id string, serverDetail model.ServerJSON, publisherExtensions map[string]interface{}) (*apiv0.ServerRecord, error) {
|
||||
func (db *PostgreSQL) UpdateServer(ctx context.Context, id string, serverDetail apiv0.ServerJSON, publisherExtensions map[string]interface{}) (*apiv0.ServerJSON, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
// First check if the server exists
|
||||
_, err := db.GetByID(ctx, id)
|
||||
// Get the existing server to preserve registry metadata
|
||||
existingServer, err := db.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Start a transaction for atomic updates
|
||||
tx, err := db.conn.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if rollbackErr := tx.Rollback(ctx); rollbackErr != nil && !errors.Is(rollbackErr, pgx.ErrTxClosed) {
|
||||
log.Printf("Failed to rollback transaction: %v", rollbackErr)
|
||||
}
|
||||
}()
|
||||
|
||||
// Prepare JSON data
|
||||
repositoryJSON, err := json.Marshal(serverDetail.Repository)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal repository: %w", err)
|
||||
// Update the server details while preserving registry metadata
|
||||
updatedServer := serverDetail
|
||||
if updatedServer.Meta == nil {
|
||||
updatedServer.Meta = &apiv0.ServerMeta{}
|
||||
}
|
||||
|
||||
packagesJSON, err := json.Marshal(serverDetail.Packages)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal packages: %w", err)
|
||||
// Preserve existing registry metadata but update timestamp
|
||||
if existingServer.Meta != nil && existingServer.Meta.IOModelContextProtocolRegistry != nil {
|
||||
updatedServer.Meta.IOModelContextProtocolRegistry = existingServer.Meta.IOModelContextProtocolRegistry
|
||||
updatedServer.Meta.IOModelContextProtocolRegistry.UpdatedAt = time.Now()
|
||||
}
|
||||
|
||||
remotesJSON, err := json.Marshal(serverDetail.Remotes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal remotes: %w", err)
|
||||
// Update publisher extensions if provided
|
||||
if len(publisherExtensions) > 0 {
|
||||
updatedServer.Meta.Publisher = publisherExtensions
|
||||
}
|
||||
|
||||
publisherExtensionsJSON, err := json.Marshal(publisherExtensions)
|
||||
// Marshal updated server
|
||||
valueJSON, err := json.Marshal(updatedServer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal publisher extensions: %w", err)
|
||||
return nil, fmt.Errorf("failed to marshal updated server: %w", err)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
// Update servers table
|
||||
serverQuery := `
|
||||
// Update the complete server record in simple table
|
||||
query := `
|
||||
UPDATE servers
|
||||
SET name = $1, description = $2, status = $3, repository = $4,
|
||||
version = $5, packages = $6, remotes = $7, updated_at = $8
|
||||
WHERE id = $9
|
||||
SET value = $1
|
||||
WHERE (value->'_meta'->'io.modelcontextprotocol.registry'->>'id') = $2
|
||||
`
|
||||
|
||||
_, err = tx.Exec(ctx, serverQuery,
|
||||
serverDetail.Name,
|
||||
serverDetail.Description,
|
||||
serverDetail.Status,
|
||||
repositoryJSON,
|
||||
serverDetail.VersionDetail.Version,
|
||||
packagesJSON,
|
||||
remotesJSON,
|
||||
now,
|
||||
id,
|
||||
)
|
||||
result, err := db.conn.Exec(ctx, query, valueJSON, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to update server: %w", err)
|
||||
}
|
||||
|
||||
// Update server_extensions table
|
||||
extQuery := `
|
||||
UPDATE server_extensions
|
||||
SET updated_at = $1, publisher_extensions = $2
|
||||
WHERE server_id = $3
|
||||
`
|
||||
|
||||
_, err = tx.Exec(ctx, extQuery, now, publisherExtensionsJSON, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to update server extensions: %w", err)
|
||||
if result.RowsAffected() == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
// Commit transaction
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, fmt.Errorf("failed to commit transaction: %w", err)
|
||||
}
|
||||
|
||||
// Return the updated record
|
||||
return db.GetByID(ctx, id)
|
||||
return &updatedServer, nil
|
||||
}
|
||||
|
||||
// Close closes the database connection
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ type fakeRegistryService struct {
|
|||
// NewFakeRegistryService creates a new fake registry service with pre-populated data
|
||||
func NewFakeRegistryService() RegistryService {
|
||||
// Sample registry entries with updated model structure using ServerJSON
|
||||
serverDetails := []*model.ServerJSON{
|
||||
serverDetails := []*apiv0.ServerJSON{
|
||||
{
|
||||
Name: "bluegreen/mcp-server",
|
||||
Description: "A dummy MCP registry for testing",
|
||||
|
|
@ -59,7 +59,7 @@ func NewFakeRegistryService() RegistryService {
|
|||
}
|
||||
|
||||
// Create a new in-memory database using registry metadata IDs
|
||||
serverDetailMap := make(map[string]*model.ServerJSON)
|
||||
serverDetailMap := make(map[string]*apiv0.ServerJSON)
|
||||
for _, entry := range serverDetails {
|
||||
registryID := uuid.New().String() // Generate registry metadata ID
|
||||
serverDetailMap[registryID] = entry
|
||||
|
|
@ -71,7 +71,7 @@ func NewFakeRegistryService() RegistryService {
|
|||
}
|
||||
|
||||
// List retrieves servers with extension wrapper format
|
||||
func (s *fakeRegistryService) List(cursor string, limit int) ([]apiv0.ServerRecord, string, error) {
|
||||
func (s *fakeRegistryService) List(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()
|
||||
|
|
@ -83,7 +83,7 @@ func (s *fakeRegistryService) List(cursor string, limit int) ([]apiv0.ServerReco
|
|||
}
|
||||
|
||||
// Return ServerRecords directly (they're now the same as ServerResponse)
|
||||
result := make([]apiv0.ServerRecord, len(serverRecords))
|
||||
result := make([]apiv0.ServerJSON, len(serverRecords))
|
||||
for i, record := range serverRecords {
|
||||
result[i] = *record
|
||||
}
|
||||
|
|
@ -92,7 +92,7 @@ func (s *fakeRegistryService) List(cursor string, limit int) ([]apiv0.ServerReco
|
|||
}
|
||||
|
||||
// GetByID retrieves a specific server by its registry metadata ID in extension wrapper format
|
||||
func (s *fakeRegistryService) GetByID(id string) (*apiv0.ServerRecord, error) {
|
||||
func (s *fakeRegistryService) GetByID(id string) (*apiv0.ServerJSON, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
|
@ -108,7 +108,7 @@ func (s *fakeRegistryService) GetByID(id string) (*apiv0.ServerRecord, error) {
|
|||
}
|
||||
|
||||
// Publish publishes a server with separated extensions
|
||||
func (s *fakeRegistryService) Publish(req apiv0.PublishRequest) (*apiv0.ServerRecord, error) {
|
||||
func (s *fakeRegistryService) 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()
|
||||
|
|
@ -118,10 +118,10 @@ func (s *fakeRegistryService) Publish(req apiv0.PublishRequest) (*apiv0.ServerRe
|
|||
return nil, err
|
||||
}
|
||||
|
||||
// Use publisher extensions directly from request
|
||||
publisherExtensions := req.XPublisher
|
||||
if publisherExtensions == nil {
|
||||
publisherExtensions = make(map[string]interface{})
|
||||
// Extract publisher extensions from _meta.publisher
|
||||
publisherExtensions := make(map[string]interface{})
|
||||
if req.Meta != nil && req.Meta.Publisher != nil {
|
||||
publisherExtensions = req.Meta.Publisher
|
||||
}
|
||||
|
||||
// Create registry metadata for fake service (always marks as latest)
|
||||
|
|
@ -135,7 +135,7 @@ func (s *fakeRegistryService) Publish(req apiv0.PublishRequest) (*apiv0.ServerRe
|
|||
}
|
||||
|
||||
// Publish to database
|
||||
serverRecord, err := s.db.Publish(ctx, req.Server, publisherExtensions, registryMetadata)
|
||||
serverRecord, err := s.db.Publish(ctx, req, publisherExtensions, registryMetadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -145,7 +145,7 @@ func (s *fakeRegistryService) Publish(req apiv0.PublishRequest) (*apiv0.ServerRe
|
|||
}
|
||||
|
||||
// EditServer updates an existing server with new details (admin operation)
|
||||
func (s *fakeRegistryService) EditServer(id string, req apiv0.PublishRequest) (*apiv0.ServerRecord, error) {
|
||||
func (s *fakeRegistryService) EditServer(id string, req apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
|
|
@ -154,14 +154,14 @@ func (s *fakeRegistryService) EditServer(id string, req apiv0.PublishRequest) (*
|
|||
return nil, err
|
||||
}
|
||||
|
||||
// Use publisher extensions directly from request
|
||||
publisherExtensions := req.XPublisher
|
||||
if publisherExtensions == nil {
|
||||
publisherExtensions = make(map[string]interface{})
|
||||
// Extract publisher extensions from _meta.publisher
|
||||
publisherExtensions := make(map[string]interface{})
|
||||
if req.Meta != nil && req.Meta.Publisher != nil {
|
||||
publisherExtensions = req.Meta.Publisher
|
||||
}
|
||||
|
||||
// Update server in database
|
||||
serverRecord, err := s.db.UpdateServer(ctx, id, req.Server, publisherExtensions)
|
||||
serverRecord, err := s.db.UpdateServer(ctx, id, req, publisherExtensions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"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
|
||||
|
|
@ -27,8 +26,8 @@ func NewRegistryServiceWithDB(db database.Database) RegistryService {
|
|||
}
|
||||
}
|
||||
|
||||
// List returns registry entries with cursor-based pagination in extension wrapper format
|
||||
func (s *registryServiceImpl) List(cursor string, limit int) ([]apiv0.ServerRecord, string, error) {
|
||||
// List returns registry entries with cursor-based pagination in flattened format
|
||||
func (s *registryServiceImpl) List(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()
|
||||
|
|
@ -44,8 +43,8 @@ func (s *registryServiceImpl) List(cursor string, limit int) ([]apiv0.ServerReco
|
|||
return nil, "", err
|
||||
}
|
||||
|
||||
// Return ServerRecords directly (they're now the same as ServerResponse)
|
||||
result := make([]apiv0.ServerRecord, len(serverRecords))
|
||||
// Return ServerJSONs directly
|
||||
result := make([]apiv0.ServerJSON, len(serverRecords))
|
||||
for i, record := range serverRecords {
|
||||
result[i] = *record
|
||||
}
|
||||
|
|
@ -53,8 +52,8 @@ func (s *registryServiceImpl) List(cursor string, limit int) ([]apiv0.ServerReco
|
|||
return result, nextCursor, nil
|
||||
}
|
||||
|
||||
// GetByID retrieves a specific server by its registry metadata ID in extension wrapper format
|
||||
func (s *registryServiceImpl) GetByID(id string) (*apiv0.ServerRecord, error) {
|
||||
// GetByID retrieves a specific server by its registry metadata ID in flattened format
|
||||
func (s *registryServiceImpl) GetByID(id string) (*apiv0.ServerJSON, error) {
|
||||
// Create a timeout context for the database operation
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
|
@ -65,12 +64,12 @@ func (s *registryServiceImpl) GetByID(id string) (*apiv0.ServerRecord, error) {
|
|||
return nil, err
|
||||
}
|
||||
|
||||
// Return ServerRecord directly (it's now the same as ServerResponse)
|
||||
// Return the server record directly
|
||||
return serverRecord, nil
|
||||
}
|
||||
|
||||
// Publish publishes a server with separated extensions
|
||||
func (s *registryServiceImpl) Publish(req apiv0.PublishRequest) (*apiv0.ServerRecord, error) {
|
||||
// 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()
|
||||
|
|
@ -81,13 +80,14 @@ func (s *registryServiceImpl) Publish(req apiv0.PublishRequest) (*apiv0.ServerRe
|
|||
}
|
||||
|
||||
publishTime := time.Now()
|
||||
serverJSON := req
|
||||
|
||||
// Check for duplicate remote URLs
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, req.Server); err != nil {
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, serverJSON); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existingServerVersions, _, err := s.db.List(ctx, map[string]any{"name": req.Server.Name}, "", maxServerVersionsPerServer)
|
||||
existingServerVersions, _, err := s.db.List(ctx, map[string]any{"name": serverJSON.Name}, "", maxServerVersionsPerServer)
|
||||
if err != nil && !errors.Is(err, database.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -99,8 +99,8 @@ func (s *registryServiceImpl) Publish(req apiv0.PublishRequest) (*apiv0.ServerRe
|
|||
|
||||
// Check this isn't a duplicate version
|
||||
for _, server := range existingServerVersions {
|
||||
existingVersion := server.Server.VersionDetail.Version
|
||||
if existingVersion == req.Server.VersionDetail.Version {
|
||||
existingVersion := server.VersionDetail.Version
|
||||
if existingVersion == serverJSON.VersionDetail.Version {
|
||||
return nil, database.ErrInvalidVersion
|
||||
}
|
||||
}
|
||||
|
|
@ -109,11 +109,15 @@ func (s *registryServiceImpl) Publish(req apiv0.PublishRequest) (*apiv0.ServerRe
|
|||
existingLatest := s.getCurrentLatestVersion(existingServerVersions)
|
||||
isNewLatest := true
|
||||
if existingLatest != nil {
|
||||
var existingPublishedAt time.Time
|
||||
if existingLatest.Meta != nil && existingLatest.Meta.IOModelContextProtocolRegistry != nil {
|
||||
existingPublishedAt = existingLatest.Meta.IOModelContextProtocolRegistry.PublishedAt
|
||||
}
|
||||
isNewLatest = CompareVersions(
|
||||
req.Server.VersionDetail.Version,
|
||||
existingLatest.Server.VersionDetail.Version,
|
||||
serverJSON.VersionDetail.Version,
|
||||
existingLatest.VersionDetail.Version,
|
||||
publishTime,
|
||||
existingLatest.XIOModelContextProtocolRegistry.PublishedAt,
|
||||
existingPublishedAt,
|
||||
) > 0
|
||||
}
|
||||
|
||||
|
|
@ -126,31 +130,37 @@ func (s *registryServiceImpl) Publish(req apiv0.PublishRequest) (*apiv0.ServerRe
|
|||
ReleaseDate: publishTime.Format(time.RFC3339),
|
||||
}
|
||||
|
||||
// Use publisher extensions directly from request
|
||||
publisherExtensions := req.XPublisher
|
||||
if publisherExtensions == nil {
|
||||
publisherExtensions = make(map[string]interface{})
|
||||
// Extract publisher extensions from _meta.publisher
|
||||
publisherExtensions := make(map[string]interface{})
|
||||
if serverJSON.Meta != nil && serverJSON.Meta.Publisher != nil {
|
||||
publisherExtensions = serverJSON.Meta.Publisher
|
||||
}
|
||||
|
||||
// Publish to database with the registry metadata
|
||||
serverRecord, err := s.db.Publish(ctx, req.Server, publisherExtensions, registryMetadata)
|
||||
// Publish to database with the registry metadata (still using old format internally)
|
||||
serverRecord, err := s.db.Publish(ctx, serverJSON, publisherExtensions, registryMetadata)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Mark previous latest as no longer latest
|
||||
if isNewLatest && existingLatest != nil {
|
||||
if err := s.db.UpdateLatestFlag(ctx, existingLatest.XIOModelContextProtocolRegistry.ID, false); err != nil {
|
||||
return nil, err
|
||||
var existingLatestID string
|
||||
if existingLatest.Meta != nil && existingLatest.Meta.IOModelContextProtocolRegistry != nil {
|
||||
existingLatestID = existingLatest.Meta.IOModelContextProtocolRegistry.ID
|
||||
}
|
||||
if existingLatestID != "" {
|
||||
if err := s.db.UpdateLatestFlag(ctx, existingLatestID, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Return ServerRecord directly (it's now the same as ServerResponse)
|
||||
// Return the server record directly
|
||||
return serverRecord, nil
|
||||
}
|
||||
|
||||
// validateNoDuplicateRemoteURLs checks that no other server is using the same remote URLs
|
||||
func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context, serverDetail model.ServerJSON) error {
|
||||
func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context, serverDetail apiv0.ServerJSON) error {
|
||||
// Check each remote URL in the new server for conflicts
|
||||
for _, remote := range serverDetail.Remotes {
|
||||
// Use filter to find servers with this remote URL
|
||||
|
|
@ -165,8 +175,8 @@ func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context,
|
|||
|
||||
// Check if any conflicting server has a different name
|
||||
for _, conflictingServer := range conflictingServers {
|
||||
if conflictingServer.Server.Name != serverDetail.Name {
|
||||
return fmt.Errorf("remote URL %s is already used by server %s", remote.URL, conflictingServer.Server.Name)
|
||||
if conflictingServer.Name != serverDetail.Name {
|
||||
return fmt.Errorf("remote URL %s is already used by server %s", remote.URL, conflictingServer.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -175,9 +185,10 @@ func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context,
|
|||
}
|
||||
|
||||
// getCurrentLatestVersion finds the current latest version from existing server versions
|
||||
func (s *registryServiceImpl) getCurrentLatestVersion(existingServerVersions []*apiv0.ServerRecord) *apiv0.ServerRecord {
|
||||
func (s *registryServiceImpl) getCurrentLatestVersion(existingServerVersions []*apiv0.ServerJSON) *apiv0.ServerJSON {
|
||||
for _, server := range existingServerVersions {
|
||||
if server.XIOModelContextProtocolRegistry.IsLatest {
|
||||
if server.Meta != nil && server.Meta.IOModelContextProtocolRegistry != nil &&
|
||||
server.Meta.IOModelContextProtocolRegistry.IsLatest {
|
||||
return server
|
||||
}
|
||||
}
|
||||
|
|
@ -185,7 +196,7 @@ func (s *registryServiceImpl) getCurrentLatestVersion(existingServerVersions []*
|
|||
}
|
||||
|
||||
// EditServer updates an existing server with new details (admin operation)
|
||||
func (s *registryServiceImpl) EditServer(id string, req apiv0.PublishRequest) (*apiv0.ServerRecord, error) {
|
||||
func (s *registryServiceImpl) EditServer(id string, req apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
|
|
@ -194,23 +205,26 @@ func (s *registryServiceImpl) EditServer(id string, req apiv0.PublishRequest) (*
|
|||
return nil, err
|
||||
}
|
||||
|
||||
serverJSON := req
|
||||
|
||||
// Check for duplicate remote URLs
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, req.Server); err != nil {
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, serverJSON); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Use publisher extensions directly from request
|
||||
publisherExtensions := req.XPublisher
|
||||
if publisherExtensions == nil {
|
||||
publisherExtensions = make(map[string]interface{})
|
||||
// Extract publisher extensions from _meta.publisher
|
||||
publisherExtensions := make(map[string]interface{})
|
||||
if serverJSON.Meta != nil && serverJSON.Meta.Publisher != nil {
|
||||
publisherExtensions = serverJSON.Meta.Publisher
|
||||
}
|
||||
|
||||
// Update server in database
|
||||
serverRecord, err := s.db.UpdateServer(ctx, id, req.Server, publisherExtensions)
|
||||
serverRecord, err := s.db.UpdateServer(ctx, id, serverJSON, publisherExtensions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Return ServerRecord directly (it's now the same as ServerResponse)
|
||||
// Return the server record directly
|
||||
return serverRecord, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,13 +6,14 @@ import (
|
|||
"testing"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
||||
// Create test data
|
||||
existingServers := map[string]*model.ServerJSON{
|
||||
existingServers := map[string]*apiv0.ServerJSON{
|
||||
"existing1": {
|
||||
Name: "com.example/existing-server",
|
||||
Description: "An existing server",
|
||||
|
|
@ -41,13 +42,13 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
|
||||
tests := []struct {
|
||||
name string
|
||||
serverDetail model.ServerJSON
|
||||
serverDetail apiv0.ServerJSON
|
||||
expectError bool
|
||||
errorMsg string
|
||||
}{
|
||||
{
|
||||
name: "no remote URLs - should pass",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/new-server",
|
||||
Description: "A new server with no remotes",
|
||||
VersionDetail: model.VersionDetail{
|
||||
|
|
@ -59,7 +60,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "new unique remote URLs - should pass",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/new-server",
|
||||
Description: "A new server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
|
|
@ -74,7 +75,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "duplicate remote URL - should fail",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/new-server",
|
||||
Description: "A new server with duplicate URL",
|
||||
VersionDetail: model.VersionDetail{
|
||||
|
|
@ -89,7 +90,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "updating same server with same URLs - should pass",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/existing-server", // Same name as existing
|
||||
Description: "Updated existing server",
|
||||
VersionDetail: model.VersionDetail{
|
||||
|
|
|
|||
|
|
@ -1,15 +1,17 @@
|
|||
package service
|
||||
|
||||
import apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
import (
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
)
|
||||
|
||||
// RegistryService defines the interface for registry operations
|
||||
type RegistryService interface {
|
||||
// List retrieves servers with unified format
|
||||
List(cursor string, limit int) ([]apiv0.ServerRecord, string, error)
|
||||
// GetByID retrieves a single server by registry metadata ID with unified format
|
||||
GetByID(id string) (*apiv0.ServerRecord, error)
|
||||
// Publish publishes a server with separated extensions
|
||||
Publish(req apiv0.PublishRequest) (*apiv0.ServerRecord, error)
|
||||
// EditServer updates an existing server with new details
|
||||
EditServer(id string, req apiv0.PublishRequest) (*apiv0.ServerRecord, error)
|
||||
// Retrieve all servers
|
||||
List(cursor string, limit int) ([]apiv0.ServerJSON, string, error)
|
||||
// Retrieve a single server by registry metadata ID
|
||||
GetByID(id 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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import (
|
|||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
func ValidateServerJSON(serverJSON *model.ServerJSON) error {
|
||||
func ValidateServerJSON(serverJSON *apiv0.ServerJSON) error {
|
||||
// Validate server name exists and format
|
||||
if _, err := parseServerName(*serverJSON); err != nil {
|
||||
return err
|
||||
|
|
@ -194,38 +194,45 @@ func validatePackage(pkg *model.Package) error {
|
|||
}
|
||||
|
||||
// ValidatePublishRequest validates a complete publish request including extensions
|
||||
func ValidatePublishRequest(req apiv0.PublishRequest) error {
|
||||
// Validate publisher extensions
|
||||
func ValidatePublishRequest(req apiv0.ServerJSON) error {
|
||||
// Validate publisher extensions in _meta
|
||||
if err := validatePublisherExtensions(req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Validate the server detail (includes all nested validation)
|
||||
if err := ValidateServerJSON(&req.Server); err != nil {
|
||||
if err := ValidateServerJSON(&req); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePublisherExtensions(req apiv0.PublishRequest) error {
|
||||
func validatePublisherExtensions(req apiv0.ServerJSON) error {
|
||||
const maxExtensionSize = 4 * 1024 // 4KB limit
|
||||
|
||||
// Check size limit for x-publisher extension
|
||||
if req.XPublisher != nil {
|
||||
extensionsJSON, err := json.Marshal(req.XPublisher)
|
||||
// Check size limit for _meta.publisher extension
|
||||
if req.Meta != nil && req.Meta.Publisher != nil {
|
||||
extensionsJSON, err := json.Marshal(req.Meta.Publisher)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal x-publisher extension: %w", err)
|
||||
return fmt.Errorf("failed to marshal _meta.publisher extension: %w", err)
|
||||
}
|
||||
if len(extensionsJSON) > maxExtensionSize {
|
||||
return fmt.Errorf("x-publisher extension exceeds 4KB limit (%d bytes)", len(extensionsJSON))
|
||||
return fmt.Errorf("_meta.publisher extension exceeds 4KB limit (%d bytes)", len(extensionsJSON))
|
||||
}
|
||||
}
|
||||
|
||||
if req.Meta != nil {
|
||||
// Validate that only "publisher" is allowed in _meta during publish (no registry metadata should be present)
|
||||
if req.Meta.IOModelContextProtocolRegistry != nil {
|
||||
return fmt.Errorf("registry metadata '_meta.io.modelcontextprotocol.registry' is not allowed during publish")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseServerName(serverJSON model.ServerJSON) (string, error) {
|
||||
func parseServerName(serverJSON apiv0.ServerJSON) (string, error) {
|
||||
name := serverJSON.Name
|
||||
if name == "" {
|
||||
return "", fmt.Errorf("server name is required and must be a string")
|
||||
|
|
@ -245,7 +252,7 @@ func parseServerName(serverJSON model.ServerJSON) (string, error) {
|
|||
}
|
||||
|
||||
// validateRemoteNamespaceMatch validates that remote URLs match the reverse-DNS namespace
|
||||
func validateRemoteNamespaceMatch(serverJSON model.ServerJSON) error {
|
||||
func validateRemoteNamespaceMatch(serverJSON apiv0.ServerJSON) error {
|
||||
namespace := serverJSON.Name
|
||||
|
||||
for _, remote := range serverJSON.Remotes {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/validators"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
|
@ -12,12 +13,12 @@ import (
|
|||
func TestValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverDetail model.ServerJSON
|
||||
serverDetail apiv0.ServerJSON
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "valid server detail with all fields",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -45,7 +46,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "server with invalid repository source",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -60,7 +61,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "server with invalid GitHub URL format",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -75,7 +76,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "server with invalid GitLab URL format",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -90,7 +91,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "package with spaces in name",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -112,7 +113,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "multiple packages with one invalid",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -139,7 +140,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "remote with invalid URL",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -159,7 +160,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "remote with missing scheme",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -179,7 +180,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "multiple remotes with one invalid",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -202,7 +203,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "server detail with nil packages and remotes",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -219,7 +220,7 @@ func TestValidate(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "server detail with empty packages and remotes slices",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -253,13 +254,13 @@ func TestValidate(t *testing.T) {
|
|||
func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverDetail model.ServerJSON
|
||||
serverDetail apiv0.ServerJSON
|
||||
expectError bool
|
||||
errorMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid match - example.com domain",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "https://example.com/mcp"},
|
||||
|
|
@ -269,7 +270,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "valid match - subdomain mcp.example.com",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "https://mcp.example.com/endpoint"},
|
||||
|
|
@ -279,7 +280,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "valid match - api subdomain",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/api-server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "https://api.example.com/mcp"},
|
||||
|
|
@ -289,7 +290,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "invalid - wrong domain",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "https://google.com/mcp"},
|
||||
|
|
@ -300,7 +301,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "invalid - different domain entirely",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.microsoft/server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "https://api.github.com/endpoint"},
|
||||
|
|
@ -311,7 +312,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "localhost URLs allowed with any namespace",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "http://localhost:3000/sse"},
|
||||
|
|
@ -321,7 +322,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "invalid URL format",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "not-a-valid-url"},
|
||||
|
|
@ -332,7 +333,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "empty remotes array",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/test",
|
||||
Remotes: []model.Remote{},
|
||||
},
|
||||
|
|
@ -340,7 +341,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "multiple valid remotes - different subdomains",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "https://api.example.com/sse"},
|
||||
|
|
@ -351,7 +352,7 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "one valid, one invalid remote",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/server",
|
||||
Remotes: []model.Remote{
|
||||
{URL: "https://example.com/sse"},
|
||||
|
|
@ -380,27 +381,27 @@ func TestValidate_RemoteNamespaceMatch(t *testing.T) {
|
|||
func TestValidate_ServerNameFormat(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverDetail model.ServerJSON
|
||||
serverDetail apiv0.ServerJSON
|
||||
expectError bool
|
||||
errorMsg string
|
||||
}{
|
||||
{
|
||||
name: "valid namespace/name format",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example.api/server",
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "valid complex namespace",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.github.microsoft.azure/webapp-server",
|
||||
},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "empty server name",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "",
|
||||
},
|
||||
expectError: true,
|
||||
|
|
@ -408,7 +409,7 @@ func TestValidate_ServerNameFormat(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "missing slash separator",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example.server",
|
||||
},
|
||||
expectError: true,
|
||||
|
|
@ -416,7 +417,7 @@ func TestValidate_ServerNameFormat(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "empty namespace part",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "/server-name",
|
||||
},
|
||||
expectError: true,
|
||||
|
|
@ -424,7 +425,7 @@ func TestValidate_ServerNameFormat(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "empty name part",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/",
|
||||
},
|
||||
expectError: true,
|
||||
|
|
@ -432,7 +433,7 @@ func TestValidate_ServerNameFormat(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "multiple slashes - uses first as separator",
|
||||
serverDetail: model.ServerJSON{
|
||||
serverDetail: apiv0.ServerJSON{
|
||||
Name: "com.example/server/path",
|
||||
},
|
||||
expectError: false,
|
||||
|
|
@ -647,8 +648,8 @@ func TestValidateArgument_ValidValueFields(t *testing.T) {
|
|||
}
|
||||
|
||||
// Helper function to create a valid server with a specific argument for testing
|
||||
func createValidServerWithArgument(arg model.Argument) model.ServerJSON {
|
||||
return model.ServerJSON{
|
||||
func createValidServerWithArgument(arg model.Argument) apiv0.ServerJSON {
|
||||
return apiv0.ServerJSON{
|
||||
Name: "com.example/test-server",
|
||||
Description: "A test server",
|
||||
Repository: model.Repository{
|
||||
|
|
@ -661,9 +662,9 @@ func createValidServerWithArgument(arg model.Argument) model.ServerJSON {
|
|||
},
|
||||
Packages: []model.Package{
|
||||
{
|
||||
Identifier: "test-package",
|
||||
RegistryType: "npm",
|
||||
RegistryBaseURL: "https://registry.npmjs.org",
|
||||
Identifier: "test-package",
|
||||
RegistryType: "npm",
|
||||
RegistryBaseURL: "https://registry.npmjs.org",
|
||||
RuntimeArguments: []model.Argument{arg},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in a new issue