Introduce serverId, rename id to versionId (#465)

Wielded Claude Code to do this; across many iterations and have reviewed
all the code + largely rewritten the PR commentary here.

This PR implements the server ID consistency changes from
[#396](https://github.com/modelcontextprotocol/registry/issues/396). Our
goal is to:
- Rename `id` to `versionId` to make it clear that it is the ID for a
specific version, not a server
- Introduce `serverId` as a net new concept. This will be 1:1 with
`name`. While not strictly necessary (we could just use name as a PK),
the convention of having a UUID as an ID on our objects is just a
helpful subjective architecture decision. Plus also leaves open the door
to reconsidering the "should we allow renames" question.

## Key Changes

### 🗄️ Database Schema Changes
- **Renamed**: `id` column → `version_id` (unique identifier for each
server version)

### 📋 Metadata Structure Updates
- **JSON Schema**: Updated
`_meta.io.modelcontextprotocol.registry/official` to include:
  - `serverId`: Consistent ID across all versions of a server
  - `versionId`: Unique ID for this specific version (renamed from `id`)

### 🔧 API Endpoint Updates
- **New endpoint structure**: Changed from version-ID-based to
server-ID-based URLs:
  - `GET /v0/servers/{server_id}` - Get latest version of server
  - `GET /v0/servers/{server_id}?version=X.X.X` - Get specific version  
- `GET /v0/servers/{server_id}/versions` - List all versions of a server
  - `PUT /v0/servers/{server_id}?version=X.X.X` - Edit specific version
- **Consistent URL patterns**: All server endpoints now use `server_id`
as the primary identifier
 
### Database Migration Strategy
The migration (`005_add_server_id_rename_version_id.sql`):
1. Adds new `version_id` column  
2. Generates deterministic UUIDs for servers with the same name
3. Updates JSON metadata to add `serverId` and rename `id` to
`versionId`
4. Copies existing `id` values to `version_id` column
5. Drops old `id` column and makes `version_id` the new primary key

## Testing

Besides of course automated tests passing, I:
1. Set up my local db with the pre-005-migration state, imported all the
production data
2. Ran the migration
3. Spot checked some diffs of the data that resulted --

```json
// before
{
  "name": "io.github.ruvnet/ruv-swarm",
  "_meta": {
    "io.modelcontextprotocol.registry/official": {
      "id": "0a9cda7f-2b73-4839-844b-6582f335de42",
      "is_latest": false,
      "updated_at": "2025-09-10T17:21:34.92137012Z",
      "published_at": "2025-09-10T17:15:32.69690433Z"
    }
  },
  "version": "1.0.18",
  "repository": {
    "url": "",
    "source": ""
  },
  "description": "Neural network swarm orchestration with WebAssembly acceleration and MCP integration"
}

// after
{
  "name": "io.github.ruvnet/ruv-swarm",
  "_meta": {
    "io.modelcontextprotocol.registry/official": {
      "serverId": "e8538952-96af-4a33-9e31-7fbed012521e",
      "is_latest": false,
      "versionId": "0a9cda7f-2b73-4839-844b-6582f335de42",
      "updated_at": "2025-09-10T17:21:34.92137012Z",
      "published_at": "2025-09-10T17:15:32.69690433Z"
    }
  },
  "version": "1.0.18",
  "repository": {
    "url": "",
    "source": ""
  },
  "description": "Neural network swarm orchestration with WebAssembly acceleration and MCP integration"
}

```

Servers that have multiple versions stayed consistent in their
`serverId`:

```json
// First version
{
  "name": "app.getdialer/dialer",
  "_meta": {
    "io.modelcontextprotocol.registry/official": {
      "serverId": "80f08bdb-f3e4-4f19-b072-1676ae49b663",
      "is_latest": false,
      "versionId": "04f25b17-331d-48d7-b08b-37baece208a7",
      "updated_at": "2025-09-09T00:16:49.162620072Z",
      "published_at": "2025-09-08T23:47:09.452137971Z"
    }
  },
  "status": "active",
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-07-09/server.schema.json",
  "remotes": [
    {
      "url": "https://getdialer.app/mcp",
      "type": "streamable-http"
    },
    {
      "url": "https://getdialer.app/sse",
      "type": "sse"
    }
  ],
  "version": "1.0.0",
  "repository": {
    "url": "",
    "source": ""
  },
  "description": "An MCP server that provides your you make outbound phone calls using your own phone number"
}

// Second version
{
  "name": "app.getdialer/dialer",
  "_meta": {
    "io.modelcontextprotocol.registry/official": {
      "serverId": "80f08bdb-f3e4-4f19-b072-1676ae49b663",
      "is_latest": true,
      "versionId": "faa26cb9-3aad-415e-aece-f715fff5fe5e",
      "updated_at": "2025-09-09T00:16:49.107842808Z",
      "published_at": "2025-09-09T00:16:49.107842808Z"
    }
  },
  "status": "active",
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-07-09/server.schema.json",
  "remotes": [
    {
      "url": "https://getdialer.app/mcp",
      "type": "streamable-http"
    },
    {
      "url": "https://getdialer.app/sse",
      "type": "sse"
    }
  ],
  "version": "1.0.1",
  "repository": {
    "url": "",
    "source": ""
  },
  "description": "An MCP server that provides lets you make outbound phone calls using your own phone number"
}
```

And I also tried publishing a test server anew; looked good:

```bash
⏺ Bash(curl -s "http://localhost:8080/v0/servers/102dc4e4-6ca8-40e6-aa11-cd45763d3352" | jq '.')
  ⎿  {                                                                                             
       "$schema": "https://static.modelcontextprotocol.io/schemas/2025-07-09/server.schema.json",
       "name": "io.modelcontextprotocol.anonymous/test-claude-migration-server",
       "description": "A test server to verify the new migration and API endpoints work correctly",
       "status": "active",
       "repository": {
         "url": "https://github.com/example/test-claude-migration-server",
         "source": "github",
         "id": "example/test-claude-migration-server"
       },
       "version": "1.0.0",
       "_meta": {
         "io.modelcontextprotocol.registry/official": {
           "serverId": "102dc4e4-6ca8-40e6-aa11-cd45763d3352",
           "versionId": "48c9cd55-7bc4-4ac2-896e-59e81eb653e4",
           "published_at": "2025-09-12T18:33:23.264203-07:00",
           "updated_at": "2025-09-12T18:33:23.264203-07:00",
           "is_latest": true
         }
       }
     }

⏺ Bash(curl -s "http://localhost:8080/v0/servers/102dc4e4-6ca8-40e6-aa11-cd45763d3352/versions" | jq '.')
  ⎿  {                                                                                                 
       "servers": [
         {
           "$schema": "https://static.modelcontextprotocol.io/schemas/2025-07-09/server.schema.json",
           "name": "io.modelcontextprotocol.anonymous/test-claude-migration-server",
           "description": "A test server to verify the new migration and API endpoints work correctly",
           "status": "active",
           "repository": {
             "url": "https://github.com/example/test-claude-migration-server",
             "source": "github",
             "id": "example/test-claude-migration-server"
           },
           "version": "1.0.0",
           "_meta": {
             "io.modelcontextprotocol.registry/official": {
               "serverId": "102dc4e4-6ca8-40e6-aa11-cd45763d3352",
               "versionId": "48c9cd55-7bc4-4ac2-896e-59e81eb653e4",
               "published_at": "2025-09-12T18:33:23.264203-07:00",
               "updated_at": "2025-09-12T18:33:23.264203-07:00",
               "is_latest": true
             }
           }
         }
       ],
       "metadata": {
         "count": 1
       }
     }
```

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Preeti Dewani <preetidewani1990@gmail.com>
Co-authored-by: adam jones <adamj+git@anthropic.com>
Co-authored-by: Adam Jones <adamj@anthropic.com>
This commit is contained in:
Tadas Antanavicius 2025-09-21 08:00:09 -04:00 • committed by GitHub
commit 56e8b4879b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 5185 additions and 3466 deletions

View file

@ -18,7 +18,8 @@ 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"`
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
Version string `query:"version" doc:"Version to edit (e.g., '1.0.0')" required:"true" example:"1.0.0"`
Body apiv0.ServerJSON `body:""`
}
@ -30,9 +31,9 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
huma.Register(api, huma.Operation{
OperationID: "edit-server",
Method: http.MethodPut,
Path: "/v0/servers/{id}",
Path: "/v0/servers/{server_id}",
Summary: "Edit MCP server",
Description: "Update an existing MCP server (admin only)",
Description: "Update an existing MCP server (admin only). Requires version query parameter to specify which version to edit.",
Tags: []string{"admin"},
Security: []map[string][]string{
{"bearer": {}},
@ -53,7 +54,8 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
}
// Get current server to check permissions against existing name
currentServer, err := registry.GetByID(input.ID)
currentServer, err := registry.GetByServerIDAndVersion(input.ServerID, input.Version)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, huma.Error404NotFound("Server not found")
@ -76,8 +78,13 @@ func RegisterEditEndpoints(api huma.API, registry service.RegistryService, cfg *
return nil, huma.Error400BadRequest("Cannot change status of deleted server. Deleted servers cannot be undeleted.")
}
// Edit the server
updatedServer, err := registry.EditServer(input.ID, input.Body)
// Edit the server using the version_id from the current server
versionID := currentServer.GetVersionID()
if versionID == "" {
return nil, huma.Error500InternalServerError("Server version ID not found in metadata", nil)
}
updatedServer, err := registry.EditServer(versionID, input.Body)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return nil, huma.Error404NotFound("Server not found")

View file

@ -42,7 +42,7 @@ func TestEditServerEndpoint(t *testing.T) {
assert.NotNil(t, published.Meta)
assert.NotNil(t, published.Meta.Official)
testServerID := published.Meta.Official.ID
testServerID := published.Meta.Official.ServerID
// Publish a second server for permission testing
otherServer := apiv0.ServerJSON{
@ -62,7 +62,7 @@ func TestEditServerEndpoint(t *testing.T) {
assert.NotNil(t, otherPublished.Meta)
assert.NotNil(t, otherPublished.Meta.Official)
otherServerID := otherPublished.Meta.Official.ID
otherServerID := otherPublished.Meta.Official.ServerID
// Publish a deleted server for undelete testing
deletedServer := apiv0.ServerJSON{
@ -82,13 +82,14 @@ func TestEditServerEndpoint(t *testing.T) {
assert.NotNil(t, deletedPublished.Meta)
assert.NotNil(t, deletedPublished.Meta.Official)
deletedServerID := deletedPublished.Meta.Official.ID
deletedServerID := deletedPublished.Meta.Official.ServerID
testCases := []struct {
name string
authHeader string
requestBody interface{}
serverID string
version string
expectedStatus int
expectedError string
}{
@ -114,9 +115,10 @@ func TestEditServerEndpoint(t *testing.T) {
Source: "github",
ID: "domdomegg/test-server",
},
Version: "1.0.1",
Version: "1.0.0",
},
serverID: testServerID,
version: "1.0.0",
expectedStatus: http.StatusOK,
},
{
@ -124,6 +126,7 @@ func TestEditServerEndpoint(t *testing.T) {
authHeader: "",
requestBody: apiv0.ServerJSON{},
serverID: testServerID,
version: "1.0.0",
expectedStatus: 422,
expectedError: "required header parameter is missing",
},
@ -131,11 +134,12 @@ func TestEditServerEndpoint(t *testing.T) {
name: "invalid authorization header format",
authHeader: "InvalidFormat token123",
requestBody: apiv0.ServerJSON{
Name: "io.github.domdomegg/test-server",
Description: "Test server",
Version: "1.0.0",
Name: "io.github.domdomegg/test-server",
Description: "Test server",
Version: "1.0.0",
},
serverID: testServerID,
version: "1.0.0",
expectedStatus: http.StatusUnauthorized,
expectedError: "Unauthorized",
},
@ -143,11 +147,12 @@ func TestEditServerEndpoint(t *testing.T) {
name: "invalid token",
authHeader: "Bearer invalid-token",
requestBody: apiv0.ServerJSON{
Name: "io.github.domdomegg/test-server",
Description: "Test server",
Version: "1.0.0",
Name: "io.github.domdomegg/test-server",
Description: "Test server",
Version: "1.0.0",
},
serverID: testServerID,
version: "1.0.0",
expectedStatus: http.StatusUnauthorized,
expectedError: "Unauthorized",
},
@ -165,11 +170,12 @@ func TestEditServerEndpoint(t *testing.T) {
return "Bearer " + token
}(),
requestBody: apiv0.ServerJSON{
Name: "io.github.domdomegg/test-server",
Description: "Updated test server",
Version: "1.0.0",
Name: "io.github.domdomegg/test-server",
Description: "Updated test server",
Version: "1.0.0",
},
serverID: testServerID,
version: "1.0.0",
expectedStatus: http.StatusForbidden,
expectedError: "Forbidden",
},
@ -187,11 +193,12 @@ func TestEditServerEndpoint(t *testing.T) {
return "Bearer " + token
}(),
requestBody: apiv0.ServerJSON{
Name: "io.github.other/test-server",
Description: "Updated test server",
Version: "1.0.0",
Name: "io.github.other/test-server",
Description: "Updated test server",
Version: "1.0.0",
},
serverID: otherServerID,
version: "1.0.0",
expectedStatus: http.StatusForbidden,
expectedError: "Forbidden",
},
@ -209,11 +216,12 @@ func TestEditServerEndpoint(t *testing.T) {
return "Bearer " + token
}(),
requestBody: apiv0.ServerJSON{
Name: "io.github.domdomegg/nonexistent-server",
Description: "Updated test server",
Version: "1.0.0",
Name: "io.github.domdomegg/nonexistent-server",
Description: "Updated test server",
Version: "1.0.0",
},
serverID: "550e8400-e29b-41d4-a716-446655440999", // Non-existent ID
version: "1.0.0",
expectedStatus: http.StatusNotFound,
expectedError: "Not Found",
},
@ -231,11 +239,12 @@ func TestEditServerEndpoint(t *testing.T) {
return "Bearer " + token
}(),
requestBody: apiv0.ServerJSON{
Name: "invalid-name-format", // Missing namespace/name format
Description: "Test server",
Version: "1.0.0",
Name: "invalid-name-format", // Missing namespace/name format
Description: "Test server",
Version: "1.0.0",
},
serverID: testServerID,
version: "1.0.0",
expectedStatus: http.StatusBadRequest,
expectedError: "Bad Request",
},
@ -264,6 +273,7 @@ func TestEditServerEndpoint(t *testing.T) {
Version: "1.0.1",
},
serverID: deletedServerID,
version: "1.0.0",
expectedStatus: http.StatusBadRequest,
expectedError: "Cannot change status of deleted server",
},
@ -293,7 +303,11 @@ func TestEditServerEndpoint(t *testing.T) {
}
// Create request
req := httptest.NewRequest(http.MethodPut, "/v0/servers/"+tc.serverID, bytes.NewReader(requestBody))
url := "/v0/servers/" + tc.serverID
if tc.version != "" {
url += "?version=" + tc.version
}
req := httptest.NewRequest(http.MethodPut, url, bytes.NewReader(requestBody))
req.Header.Set("Content-Type", "application/json")
if tc.authHeader != "" {
req.Header.Set("Authorization", tc.authHeader)

View file

@ -2,6 +2,7 @@ package v0
import (
"context"
"errors"
"net/http"
"time"
@ -23,7 +24,13 @@ type ListServersInput struct {
// ServerDetailInput represents the input for getting server details
type ServerDetailInput struct {
ID string `path:"id" doc:"Server ID (UUID)" format:"uuid"`
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
Version string `query:"version" doc:"Specific version to retrieve (e.g., '1.0.0'). If not specified, returns latest version." required:"false" example:"1.0.0"`
}
// ServerVersionsInput represents the input for listing all versions of a server
type ServerVersionsInput struct {
ServerID string `path:"server_id" doc:"Server ID (UUID)" format:"uuid"`
}
// RegisterServersEndpoints registers all server-related endpoints
@ -96,15 +103,25 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
huma.Register(api, huma.Operation{
OperationID: "get-server",
Method: http.MethodGet,
Path: "/v0/servers/{id}",
Path: "/v0/servers/{server_id}",
Summary: "Get MCP server details",
Description: "Get detailed information about a specific MCP server",
Description: "Get detailed information about a specific MCP server. Returns the latest version by default, or a specific version if the 'version' query parameter is provided.",
Tags: []string{"servers"},
}, func(_ context.Context, input *ServerDetailInput) (*Response[apiv0.ServerJSON], error) {
// Get the server details from the registry service
serverDetail, err := registry.GetByID(input.ID)
var serverDetail *apiv0.ServerJSON
var err error
if input.Version != "" {
// Get specific version by server_id and version
serverDetail, err = registry.GetByServerIDAndVersion(input.ServerID, input.Version)
} else {
// Get latest version by server_id
serverDetail, err = registry.GetByServerID(input.ServerID)
}
if err != nil {
if err.Error() == "record not found" {
if err.Error() == "record not found" || errors.Is(err, database.ErrNotFound) {
return nil, huma.Error404NotFound("Server not found")
}
return nil, huma.Error500InternalServerError("Failed to get server details", err)
@ -114,4 +131,32 @@ func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
Body: *serverDetail,
}, nil
})
// Get server versions endpoint
huma.Register(api, huma.Operation{
OperationID: "get-server-versions",
Method: http.MethodGet,
Path: "/v0/servers/{server_id}/versions",
Summary: "Get all versions of an MCP server",
Description: "Get all available versions for a specific MCP server",
Tags: []string{"servers"},
}, func(_ context.Context, input *ServerVersionsInput) (*Response[apiv0.ServerListResponse], error) {
// Get all versions for this server
servers, err := registry.GetAllVersionsByServerID(input.ServerID)
if err != nil {
if err.Error() == "record not found" {
return nil, huma.Error404NotFound("Server not found")
}
return nil, huma.Error500InternalServerError("Failed to get server versions", err)
}
return &Response[apiv0.ServerListResponse]{
Body: apiv0.ServerListResponse{
Servers: servers,
Metadata: apiv0.Metadata{
Count: len(servers),
},
},
}, nil
})
}

View file

@ -354,7 +354,7 @@ func TestServersListEndpoint(t *testing.T) {
assert.NotEmpty(t, server.Description)
assert.NotNil(t, server.Meta)
assert.NotNil(t, server.Meta.Official)
assert.NotEmpty(t, server.Meta.Official.ID)
assert.NotEmpty(t, server.Meta.Official.VersionID)
}
// Check metadata if expected
@ -380,25 +380,53 @@ func TestServersDetailEndpoint(t *testing.T) {
// Create mock registry service
registryService := service.NewRegistryService(database.NewMemoryDB(), config.NewConfig())
testServer, err := registryService.Publish(apiv0.ServerJSON{
// Publish multiple versions of the same server
testServer1, err := registryService.Publish(apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
Version: "1.0.0",
})
assert.NoError(t, err)
_, err = registryService.Publish(apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server updated",
Version: "2.0.0",
})
assert.NoError(t, err)
testCases := []struct {
name string
serverID string
version string
expectedStatus int
expectedServer *apiv0.ServerJSON
expectedError string
}{
{
name: "successful get server detail",
serverID: testServer.Meta.Official.ID,
name: "successful get server detail (latest)",
serverID: testServer1.Meta.Official.ServerID,
expectedStatus: http.StatusOK,
},
{
name: "successful get server detail with specific version",
serverID: testServer1.Meta.Official.ServerID,
version: "1.0.0",
expectedStatus: http.StatusOK,
},
{
name: "successful get server detail with latest version",
serverID: testServer1.Meta.Official.ServerID,
version: "2.0.0",
expectedStatus: http.StatusOK,
},
{
name: "version not found for server",
serverID: testServer1.Meta.Official.ServerID,
version: "3.0.0",
expectedStatus: http.StatusNotFound,
expectedError: "Server not found",
},
{
name: "invalid server ID format",
serverID: "invalid-uuid",
@ -424,6 +452,9 @@ func TestServersDetailEndpoint(t *testing.T) {
// Create request
url := "/v0/servers/" + tc.serverID
if tc.version != "" {
url += "?version=" + tc.version
}
req := httptest.NewRequest(http.MethodGet, url, nil)
w := httptest.NewRecorder()
@ -455,6 +486,115 @@ func TestServersDetailEndpoint(t *testing.T) {
}
}
func TestServersVersionsEndpoint(t *testing.T) {
// Create mock registry service
registryService := service.NewRegistryService(database.NewMemoryDB(), config.NewConfig())
// Publish multiple versions of the same server
testServer1, err := registryService.Publish(apiv0.ServerJSON{
Name: "com.example/versioned-server",
Description: "A versioned test server",
Version: "1.0.0",
})
assert.NoError(t, err)
_, err = registryService.Publish(apiv0.ServerJSON{
Name: "com.example/versioned-server",
Description: "A versioned test server updated",
Version: "2.0.0",
})
assert.NoError(t, err)
_, err = registryService.Publish(apiv0.ServerJSON{
Name: "com.example/versioned-server",
Description: "A versioned test server latest",
Version: "2.1.0",
})
assert.NoError(t, err)
testCases := []struct {
name string
serverID string
expectedStatus int
expectedCount int
expectedError string
}{
{
name: "successful get all versions",
serverID: testServer1.Meta.Official.ServerID,
expectedStatus: http.StatusOK,
expectedCount: 3,
},
{
name: "invalid server ID format",
serverID: "invalid-uuid",
expectedStatus: http.StatusUnprocessableEntity,
expectedError: "validation failed",
},
{
name: "server not found",
serverID: uuid.New().String(),
expectedStatus: http.StatusNotFound,
expectedError: "Server not found",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create a new test API
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
// Register the servers endpoints
v0.RegisterServersEndpoints(api, registryService)
// Create request
url := "/v0/servers/" + tc.serverID + "/versions"
req := httptest.NewRequest(http.MethodGet, url, nil)
w := httptest.NewRecorder()
// Serve the request
mux.ServeHTTP(w, req)
// Check status code
assert.Equal(t, tc.expectedStatus, w.Code)
if tc.expectedStatus == http.StatusOK {
// Check content type
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
// Parse response body
var versionsResp apiv0.ServerListResponse
err := json.NewDecoder(w.Body).Decode(&versionsResp)
assert.NoError(t, err)
// Check the response data
assert.Len(t, versionsResp.Servers, tc.expectedCount)
assert.Equal(t, tc.expectedCount, versionsResp.Metadata.Count)
// Verify all returned servers have the same server ID but different versions
for _, server := range versionsResp.Servers {
assert.Equal(t, tc.serverID, server.Meta.Official.ServerID)
assert.NotEmpty(t, server.Version)
assert.Equal(t, "com.example/versioned-server", server.Name)
}
// Verify versions are included (should have 1.0.0, 2.0.0, 2.1.0)
versions := make([]string, 0, len(versionsResp.Servers))
for _, server := range versionsResp.Servers {
versions = append(versions, server.Version)
}
assert.Contains(t, versions, "1.0.0")
assert.Contains(t, versions, "2.0.0")
assert.Contains(t, versions, "2.1.0")
} else if tc.expectedError != "" {
// Check error message for non-200 responses
assert.Contains(t, w.Body.String(), tc.expectedError)
}
})
}
}
// TestServersEndpointsIntegration tests the servers endpoints with actual HTTP requests
func TestServersEndpointsIntegration(t *testing.T) {
// Create mock registry service
@ -476,7 +616,7 @@ func TestServersEndpointsIntegration(t *testing.T) {
assert.NoError(t, err)
assert.NotNil(t, published)
serverID := published.Meta.Official.ID
serverID := published.Meta.Official.ServerID
servers := []apiv0.ServerJSON{*published}
serverDetail := published

View file

@ -51,7 +51,7 @@ func TestPrometheusHandler(t *testing.T) {
mux.Handle("/metrics", metrics.PrometheusHandler())
// Create request
url := "/v0/servers/" + server.Meta.Official.ID
url := "/v0/servers/" + server.Meta.Official.ServerID
req := httptest.NewRequest(http.MethodGet, url, nil)
w := httptest.NewRecorder()
@ -76,5 +76,5 @@ func TestPrometheusHandler(t *testing.T) {
// Check if the response body contains expected metrics
assert.Contains(t, body, "mcp_registry_http_request_duration_bucket")
assert.Contains(t, body, "mcp_registry_http_requests_total")
assert.Contains(t, body, "path=\"/v0/servers/{id}\"")
assert.Contains(t, body, "path=\"/v0/servers/{server_id}\"")
}

View file

@ -32,8 +32,14 @@ type ServerFilter struct {
type Database interface {
// Retrieve server entries with optional filtering
List(ctx context.Context, filter *ServerFilter, cursor string, limit int) ([]*apiv0.ServerJSON, string, error)
// Retrieve a single server by its ID
GetByID(ctx context.Context, id string) (*apiv0.ServerJSON, error)
// Retrieve a single server by its version ID
GetByVersionID(ctx context.Context, versionID string) (*apiv0.ServerJSON, error)
// Retrieve latest version of a server by server ID
GetByServerID(ctx context.Context, serverID string) (*apiv0.ServerJSON, error)
// Retrieve specific version of a server by server ID and version
GetByServerIDAndVersion(ctx context.Context, serverID string, version string) (*apiv0.ServerJSON, error)
// Retrieve all versions of a server by server ID
GetAllVersionsByServerID(ctx context.Context, serverID string) ([]*apiv0.ServerJSON, error)
// CreateServer adds a new server to the database
CreateServer(ctx context.Context, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error)
// UpdateServer updates an existing server record

View file

@ -12,7 +12,7 @@ import (
// MemoryDB is an in-memory implementation of the Database interface
type MemoryDB struct {
entries map[string]*apiv0.ServerJSON // maps registry metadata ID to ServerJSON
entries map[string]*apiv0.ServerJSON // maps registry metadata version_id to ServerJSON
mu sync.RWMutex
}
@ -80,7 +80,7 @@ func (db *MemoryDB) List(
return result, nextCursor, nil
}
func (db *MemoryDB) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON, error) {
func (db *MemoryDB) GetByVersionID(ctx context.Context, versionID string) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
@ -88,8 +88,8 @@ func (db *MemoryDB) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON,
db.mu.RLock()
defer db.mu.RUnlock()
// Find entry by registry metadata ID
if entry, exists := db.entries[id]; exists {
// Find entry by registry metadata version_id
if entry, exists := db.entries[versionID]; exists {
// Return a copy of the ServerRecord
entryCopy := *entry
return &entryCopy, nil
@ -98,23 +98,112 @@ func (db *MemoryDB) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON,
return nil, ErrNotFound
}
// GetByServerID retrieves the latest version of a server by server ID
func (db *MemoryDB) GetByServerID(ctx context.Context, serverID string) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
db.mu.RLock()
defer db.mu.RUnlock()
// Find the latest version with the given server ID
var latestEntry *apiv0.ServerJSON
for _, entry := range db.entries {
if entry.Meta != nil && entry.Meta.Official != nil &&
entry.Meta.Official.ServerID == serverID &&
entry.Meta.Official.IsLatest {
latestEntry = entry
break
}
}
if latestEntry == nil {
return nil, ErrNotFound
}
// Return a copy
entryCopy := *latestEntry
return &entryCopy, nil
}
// GetByServerIDAndVersion retrieves a specific version of a server by server ID and version
func (db *MemoryDB) GetByServerIDAndVersion(ctx context.Context, serverID string, version string) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
db.mu.RLock()
defer db.mu.RUnlock()
// Find the entry with matching server ID and version
for _, entry := range db.entries {
if entry.Meta != nil && entry.Meta.Official != nil &&
entry.Meta.Official.ServerID == serverID &&
entry.Version == version {
// Return a copy
entryCopy := *entry
return &entryCopy, nil
}
}
return nil, ErrNotFound
}
// GetAllVersionsByServerID retrieves all versions of a server by server ID
func (db *MemoryDB) GetAllVersionsByServerID(ctx context.Context, serverID string) ([]*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
db.mu.RLock()
defer db.mu.RUnlock()
var results []*apiv0.ServerJSON
for _, entry := range db.entries {
if entry.Meta != nil && entry.Meta.Official != nil &&
entry.Meta.Official.ServerID == serverID {
// Add a copy
entryCopy := *entry
results = append(results, &entryCopy)
}
}
if len(results) == 0 {
return nil, ErrNotFound
}
// Sort by published date, latest first
sort.Slice(results, func(i, j int) bool {
iTime := results[i].Meta.Official.PublishedAt
jTime := results[j].Meta.Official.PublishedAt
return iTime.After(jTime)
})
return results, nil
}
func (db *MemoryDB) CreateServer(ctx context.Context, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Get the ID from the registry metadata
// Get the VersionID from the registry metadata
if server.Meta == nil || server.Meta.Official == nil {
return nil, fmt.Errorf("server must have registry metadata with ID")
return nil, fmt.Errorf("server must have registry metadata with ServerID and VersionID")
}
id := server.Meta.Official.ID
versionID := server.Meta.Official.VersionID
if versionID == "" {
return nil, fmt.Errorf("server must have VersionID in registry metadata")
}
db.mu.Lock()
defer db.mu.Unlock()
// Store the record using registry metadata ID
db.entries[id] = server
// Store the record using registry metadata VersionID
db.entries[versionID] = server
return server, nil
}
@ -124,6 +213,11 @@ func (db *MemoryDB) UpdateServer(ctx context.Context, id string, server *apiv0.S
return nil, ctx.Err()
}
// Validate that meta structure exists and VersionID matches path (consistent with PostgreSQL implementation)
if server.Meta == nil || server.Meta.Official == nil || server.Meta.Official.VersionID != id {
return nil, fmt.Errorf("%w: io.modelcontextprotocol.registry/official.version_id must match path id (%s)", ErrInvalidInput, id)
}
db.mu.Lock()
defer db.mu.Unlock()
@ -165,6 +259,7 @@ func (db *MemoryDB) filterAndSort(allEntries []*apiv0.ServerJSON, filter *Server
}
// matchesFilter checks if an entry matches the provided filter
//
//nolint:cyclop // Filter matching logic is inherently complex but clear
func (db *MemoryDB) matchesFilter(entry *apiv0.ServerJSON, filter *ServerFilter) bool {
if filter == nil {
@ -218,7 +313,7 @@ func (db *MemoryDB) matchesFilter(entry *apiv0.ServerJSON, filter *ServerFilter)
}
}
// Check is_latest filter
// Check isLatest filter
if filter.IsLatest != nil {
if entry.Meta == nil || entry.Meta.Official == nil {
return false
@ -231,10 +326,10 @@ func (db *MemoryDB) matchesFilter(entry *apiv0.ServerJSON, filter *ServerFilter)
return true
}
// getRegistryID safely extracts the registry ID from an entry
// getRegistryID safely extracts the registry version ID from an entry
func (db *MemoryDB) getRegistryID(entry *apiv0.ServerJSON) string {
if entry.Meta != nil && entry.Meta.Official != nil {
return entry.Meta.Official.ID
return entry.Meta.Official.VersionID
}
return ""
}

View file

@ -0,0 +1,90 @@
-- Migration to rename id to version_id and update JSON metadata
-- This implements the server ID consistency changes from GitHub issue #396
--
-- Current schema: servers(id VARCHAR, value JSONB)
-- Target schema: servers(version_id VARCHAR, value JSONB)
-- JSON metadata changes:
-- - rename "id" to "versionId"
-- - add "serverId" (consistent across versions of same server)
BEGIN;
-- Add the new version_id column
ALTER TABLE servers ADD COLUMN version_id VARCHAR(255);
-- Create a temporary function to:
-- 1. Migrate id -> version_id column
-- 2. Update JSON metadata to add serverId and rename id to versionId
CREATE OR REPLACE FUNCTION migrate_to_server_version_ids()
RETURNS VOID AS $$
DECLARE
rec RECORD;
server_name TEXT;
server_id_map JSONB := '{}';
new_server_id UUID;
updated_meta JSONB;
updated_value JSONB;
BEGIN
-- Iterate through all records and assign server_id and version_id
FOR rec IN SELECT id, value FROM servers ORDER BY id LOOP
-- Extract server name from the JSONB value
server_name := rec.value->>'name';
-- Check if we already have a server_id for this server name
IF (server_id_map ? server_name) THEN
new_server_id := (server_id_map->>server_name)::UUID;
ELSE
-- Generate a new server_id for this server name
new_server_id := uuid_generate_v4();
server_id_map := jsonb_set(server_id_map, ARRAY[server_name], to_jsonb(new_server_id::TEXT));
END IF;
-- Update the JSON metadata
updated_meta := rec.value->'_meta'->'io.modelcontextprotocol.registry/official';
-- Add serverId and rename id to versionId
updated_meta := updated_meta || jsonb_build_object(
'serverId', new_server_id::TEXT,
'versionId', updated_meta->>'id'
);
-- Remove the old 'id' field
updated_meta := updated_meta - 'id';
-- Update the full value with new metadata
updated_value := jsonb_set(
rec.value,
'{_meta,io.modelcontextprotocol.registry/official}',
updated_meta
);
-- Update the record with version_id and updated JSON
UPDATE servers
SET
version_id = rec.id,
value = updated_value
WHERE id = rec.id;
END LOOP;
END;
$$ LANGUAGE plpgsql;
-- Execute the migration function
SELECT migrate_to_server_version_ids();
-- Drop the temporary function
DROP FUNCTION migrate_to_server_version_ids();
-- Make version_id NOT NULL now that all records have values
ALTER TABLE servers ALTER COLUMN version_id SET NOT NULL;
-- Drop the old id column (replaced by version_id)
ALTER TABLE servers DROP COLUMN id;
-- Make version_id the new primary key
ALTER TABLE servers ADD CONSTRAINT servers_pkey PRIMARY KEY (version_id);
-- Update existing indexes to use version_id instead of id
DROP INDEX IF EXISTS idx_servers_id;
CREATE INDEX idx_servers_version_id ON servers(version_id);
COMMIT;

View file

@ -11,6 +11,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
)
@ -50,7 +51,7 @@ func NewPostgreSQL(ctx context.Context, connectionURI string) (*PostgreSQL, erro
return nil, fmt.Errorf("failed to acquire connection for migrations: %w", err)
}
defer conn.Release()
migrator := NewMigrator(conn.Conn())
if err := migrator.Migrate(ctx); err != nil {
return nil, fmt.Errorf("failed to run database migrations: %w", err)
@ -94,7 +95,7 @@ func (db *PostgreSQL) List(
argIndex++
}
if filter.UpdatedSince != nil {
whereConditions = append(whereConditions, fmt.Sprintf("(value->'_meta'->'io.modelcontextprotocol.registry/official'->>'updated_at')::timestamp > $%d", argIndex))
whereConditions = append(whereConditions, fmt.Sprintf("(value->'_meta'->'io.modelcontextprotocol.registry/official'->>'updatedAt')::timestamp > $%d", argIndex))
args = append(args, *filter.UpdatedSince)
argIndex++
}
@ -109,18 +110,18 @@ func (db *PostgreSQL) List(
argIndex++
}
if filter.IsLatest != nil {
whereConditions = append(whereConditions, fmt.Sprintf("(value->'_meta'->'io.modelcontextprotocol.registry/official'->>'is_latest')::boolean = $%d", argIndex))
whereConditions = append(whereConditions, fmt.Sprintf("(value->'_meta'->'io.modelcontextprotocol.registry/official'->>'isLatest')::boolean = $%d", argIndex))
args = append(args, *filter.IsLatest)
argIndex++
}
}
// Add cursor pagination using primary key ID
// Add cursor pagination using primary key version_id
if cursor != "" {
if _, err := uuid.Parse(cursor); err != nil {
return nil, "", fmt.Errorf("invalid cursor format: %w", err)
}
whereConditions = append(whereConditions, fmt.Sprintf("id > $%d", argIndex))
whereConditions = append(whereConditions, fmt.Sprintf("version_id > $%d", argIndex))
args = append(args, cursor)
argIndex++
}
@ -136,7 +137,7 @@ func (db *PostgreSQL) List(
SELECT value
FROM servers
%s
ORDER BY id
ORDER BY version_id
LIMIT $%d
`, whereClause, argIndex)
args = append(args, limit)
@ -169,19 +170,19 @@ func (db *PostgreSQL) List(
return nil, "", fmt.Errorf("error iterating rows: %w", err)
}
// Determine next cursor using registry metadata ID
// Determine next cursor using registry metadata VersionID
nextCursor := ""
if len(results) > 0 && len(results) >= limit {
lastResult := results[len(results)-1]
if lastResult.Meta != nil && lastResult.Meta.Official != nil {
nextCursor = lastResult.Meta.Official.ID
nextCursor = lastResult.Meta.Official.VersionID
}
}
return results, nextCursor, nil
}
func (db *PostgreSQL) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON, error) {
func (db *PostgreSQL) GetByVersionID(ctx context.Context, versionID string) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
@ -189,12 +190,12 @@ func (db *PostgreSQL) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON
query := `
SELECT value
FROM servers
WHERE id = $1
WHERE version_id = $1
`
var valueJSON []byte
err := db.pool.QueryRow(ctx, query, id).Scan(&valueJSON)
err := db.pool.QueryRow(ctx, query, versionID).Scan(&valueJSON)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@ -212,18 +213,138 @@ func (db *PostgreSQL) GetByID(ctx context.Context, id string) (*apiv0.ServerJSON
return &serverJSON, nil
}
// GetByServerID retrieves the latest version of a server by server ID
func (db *PostgreSQL) GetByServerID(ctx context.Context, serverID string) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
query := `
SELECT value
FROM servers
WHERE (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'serverId') = $1 AND (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'isLatest')::boolean = true
ORDER BY (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'publishedAt')::timestamp DESC
LIMIT 1
`
var valueJSON []byte
err := db.pool.QueryRow(ctx, query, serverID).Scan(&valueJSON)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("failed to get server by server ID: %w", err)
}
// Parse the complete ServerJSON from JSONB
var serverJSON apiv0.ServerJSON
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
}
return &serverJSON, nil
}
// GetByServerIDAndVersion retrieves a specific version of a server by server ID and version
func (db *PostgreSQL) GetByServerIDAndVersion(ctx context.Context, serverID string, version string) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
query := `
SELECT value
FROM servers
WHERE (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'serverId') = $1 AND value->>'version' = $2
LIMIT 1
`
var valueJSON []byte
err := db.pool.QueryRow(ctx, query, serverID, version).Scan(&valueJSON)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("failed to get server by server ID and version: %w", err)
}
// Parse the complete ServerJSON from JSONB
var serverJSON apiv0.ServerJSON
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
}
return &serverJSON, nil
}
// GetAllVersionsByServerID retrieves all versions of a server by server ID
func (db *PostgreSQL) GetAllVersionsByServerID(ctx context.Context, serverID string) ([]*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
query := `
SELECT value
FROM servers
WHERE (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'serverId') = $1
ORDER BY (value->'_meta'->'io.modelcontextprotocol.registry/official'->>'publishedAt')::timestamp DESC
`
rows, err := db.pool.Query(ctx, query, serverID)
if err != nil {
return nil, fmt.Errorf("failed to query server versions: %w", err)
}
defer rows.Close()
var results []*apiv0.ServerJSON
for rows.Next() {
var valueJSON []byte
err := rows.Scan(&valueJSON)
if err != nil {
return nil, fmt.Errorf("failed to scan server row: %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)
}
results = append(results, &serverJSON)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("error iterating rows: %w", err)
}
if len(results) == 0 {
return nil, ErrNotFound
}
return results, nil
}
// CreateServer adds a new server to the database
func (db *PostgreSQL) CreateServer(ctx context.Context, server *apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Get the ID from the registry metadata
// Get the IDs from the registry metadata
if server.Meta == nil || server.Meta.Official == nil {
return nil, fmt.Errorf("server must have registry metadata with ID")
return nil, fmt.Errorf("server must have registry metadata with ServerID and VersionID")
}
id := server.Meta.Official.ID
serverID := server.Meta.Official.ServerID
versionID := server.Meta.Official.VersionID
if serverID == "" || versionID == "" {
return nil, fmt.Errorf("server must have both ServerID and VersionID in registry metadata")
}
// Marshal the complete server to JSONB
valueJSON, err := json.Marshal(server)
@ -231,13 +352,13 @@ func (db *PostgreSQL) CreateServer(ctx context.Context, server *apiv0.ServerJSON
return nil, fmt.Errorf("failed to marshal server JSON: %w", err)
}
// Insert into simple servers table
// Insert into servers table with new schema (only version_id column, serverId is in JSON)
query := `
INSERT INTO servers (id, value)
INSERT INTO servers (version_id, value)
VALUES ($1, $2)
`
_, err = db.pool.Exec(ctx, query, id, valueJSON)
_, err = db.pool.Exec(ctx, query, versionID, valueJSON)
if err != nil {
return nil, fmt.Errorf("failed to insert server: %w", err)
}
@ -251,9 +372,9 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, id string, server *apiv0
return nil, ctx.Err()
}
// Validate that meta structure exists and ID matches path
if server.Meta == nil || server.Meta.Official == nil || server.Meta.Official.ID != id {
return nil, fmt.Errorf("%w: io.modelcontextprotocol.registry/official.id must match path id (%s)", ErrInvalidInput, id)
// Validate that meta structure exists and VersionID matches path
if server.Meta == nil || server.Meta.Official == nil || server.Meta.Official.VersionID != id {
return nil, fmt.Errorf("%w: io.modelcontextprotocol.registry/official.version_id must match path id (%s)", ErrInvalidInput, id)
}
// Marshal updated server
@ -262,11 +383,11 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, id string, server *apiv0
return nil, fmt.Errorf("failed to marshal updated server: %w", err)
}
// Update the complete server record in simple table
// Update the complete server record using version_id
query := `
UPDATE servers
SET value = $1
WHERE id = $2
WHERE version_id = $2
`
result, err := db.pool.Exec(ctx, query, valueJSON, id)

View file

@ -32,7 +32,8 @@ func TestImportService_LocalFile(t *testing.T) {
Version: "1.0.0",
Meta: &apiv0.ServerMeta{
Official: &apiv0.RegistryExtensions{
ID: "test-id-1",
ServerID: "server-id-1",
VersionID: "test-id-1",
PublishedAt: time.Now(),
UpdatedAt: time.Now(),
IsLatest: true,
@ -76,7 +77,8 @@ func TestImportService_HTTPFile(t *testing.T) {
Version: "2.0.0",
Meta: &apiv0.ServerMeta{
Official: &apiv0.RegistryExtensions{
ID: "test-id-2",
ServerID: "server-id-test",
VersionID: "test-id-2",
PublishedAt: time.Now(),
UpdatedAt: time.Now(),
IsLatest: true,
@ -119,7 +121,8 @@ func TestImportService_RegistryAPI(t *testing.T) {
Version: "1.0.0",
Meta: &apiv0.ServerMeta{
Official: &apiv0.RegistryExtensions{
ID: "api-test-id-1",
ServerID: "server-id-test",
VersionID: "api-test-id-1",
PublishedAt: time.Now(),
UpdatedAt: time.Now(),
IsLatest: true,
@ -137,7 +140,8 @@ func TestImportService_RegistryAPI(t *testing.T) {
Version: "2.0.0",
Meta: &apiv0.ServerMeta{
Official: &apiv0.RegistryExtensions{
ID: "api-test-id-2",
ServerID: "server-id-test",
VersionID: "api-test-id-2",
PublishedAt: time.Now(),
UpdatedAt: time.Now(),
IsLatest: true,

View file

@ -55,13 +55,13 @@ func (s *registryServiceImpl) List(filter *database.ServerFilter, cursor string,
return result, nextCursor, nil
}
// GetByID retrieves a specific server by its registry metadata ID in flattened format
func (s *registryServiceImpl) GetByID(id string) (*apiv0.ServerJSON, error) {
// GetByVersionID retrieves a specific server by its registry metadata version ID
func (s *registryServiceImpl) GetByVersionID(versionID string) (*apiv0.ServerJSON, error) {
// Create a timeout context for the database operation
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
serverRecord, err := s.db.GetByID(ctx, id)
serverRecord, err := s.db.GetByVersionID(ctx, versionID)
if err != nil {
return nil, err
}
@ -70,6 +70,56 @@ func (s *registryServiceImpl) GetByID(id string) (*apiv0.ServerJSON, error) {
return serverRecord, nil
}
// GetByServerID retrieves the latest version of a server by its server ID
func (s *registryServiceImpl) GetByServerID(serverID string) (*apiv0.ServerJSON, error) {
// Create a timeout context for the database operation
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
serverRecord, err := s.db.GetByServerID(ctx, serverID)
if err != nil {
return nil, err
}
// Return the server record directly
return serverRecord, nil
}
// GetByServerIDAndVersion retrieves a specific version of a server by server ID and version
func (s *registryServiceImpl) GetByServerIDAndVersion(serverID string, version string) (*apiv0.ServerJSON, error) {
// Create a timeout context for the database operation
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
serverRecord, err := s.db.GetByServerIDAndVersion(ctx, serverID, version)
if err != nil {
return nil, err
}
// Return the server record directly
return serverRecord, nil
}
// GetAllVersionsByServerID retrieves all versions of a server by server ID
func (s *registryServiceImpl) GetAllVersionsByServerID(serverID string) ([]apiv0.ServerJSON, error) {
// Create a timeout context for the database operation
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
serverRecords, err := s.db.GetAllVersionsByServerID(ctx, serverID)
if err != nil {
return nil, err
}
// Return ServerJSONs directly
result := make([]apiv0.ServerJSON, len(serverRecords))
for i, record := range serverRecords {
result[i] = *record
}
return result, nil
}
// Publish publishes a server with flattened _meta extensions
func (s *registryServiceImpl) Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
// Create a timeout context for the database operation
@ -125,20 +175,7 @@ func (s *registryServiceImpl) Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON,
}
// Create complete server with metadata
server := serverJSON // Copy the input
// Initialize meta if not present
if server.Meta == nil {
server.Meta = &apiv0.ServerMeta{}
}
// Set registry metadata
server.Meta.Official = &apiv0.RegistryExtensions{
ID: uuid.New().String(),
PublishedAt: publishTime,
UpdatedAt: publishTime,
IsLatest: isNewLatest,
}
server := s.createServerWithMetadata(serverJSON, existingServerVersions, publishTime, isNewLatest)
// Create server in database
serverRecord, err := s.db.CreateServer(ctx, &server)
@ -148,15 +185,15 @@ func (s *registryServiceImpl) Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON,
// Mark previous latest as no longer latest
if isNewLatest && existingLatest != nil {
var existingLatestID string
var existingLatestVersionID string
if existingLatest.Meta != nil && existingLatest.Meta.Official != nil {
existingLatestID = existingLatest.Meta.Official.ID
existingLatestVersionID = existingLatest.Meta.Official.VersionID
}
if existingLatestID != "" {
// Update the existing server to set is_latest = false
if existingLatestVersionID != "" {
// Update the existing server to set isLatest = false
existingLatest.Meta.Official.IsLatest = false
existingLatest.Meta.Official.UpdatedAt = time.Now()
if _, err := s.db.UpdateServer(ctx, existingLatestID, existingLatest); err != nil {
if _, err := s.db.UpdateServer(ctx, existingLatestVersionID, existingLatest); err != nil {
return nil, err
}
}
@ -166,6 +203,46 @@ func (s *registryServiceImpl) Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON,
return serverRecord, nil
}
// createServerWithMetadata creates a server with proper metadata including server_id and version_id
func (s *registryServiceImpl) createServerWithMetadata(
serverJSON apiv0.ServerJSON,
existingServerVersions []*apiv0.ServerJSON,
publishTime time.Time,
isNewLatest bool,
) apiv0.ServerJSON {
server := serverJSON // Copy the input
// Initialize meta if not present
if server.Meta == nil {
server.Meta = &apiv0.ServerMeta{}
}
// Determine server_id - either from existing versions or generate new one
var serverID string
if len(existingServerVersions) > 0 {
// Use existing server_id from any existing version
firstExisting := existingServerVersions[0]
if firstExisting.Meta != nil && firstExisting.Meta.Official != nil {
serverID = firstExisting.Meta.Official.ServerID
}
}
if serverID == "" {
// This is the first version of a new server
serverID = uuid.New().String()
}
// Set registry metadata
server.Meta.Official = &apiv0.RegistryExtensions{
ServerID: serverID,
VersionID: uuid.New().String(),
PublishedAt: publishTime,
UpdatedAt: publishTime,
IsLatest: isNewLatest,
}
return server
}
// validateNoDuplicateRemoteURLs checks that no other server is using the same remote URLs
func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context, serverDetail apiv0.ServerJSON) error {
// Check each remote URL in the new server for conflicts
@ -201,24 +278,45 @@ func (s *registryServiceImpl) getCurrentLatestVersion(existingServerVersions []*
}
// EditServer updates an existing server with new details (admin operation)
func (s *registryServiceImpl) EditServer(id string, req apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
func (s *registryServiceImpl) EditServer(versionID string, req apiv0.ServerJSON) (*apiv0.ServerJSON, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// First get the current server to preserve metadata
currentServer, err := s.db.GetByVersionID(ctx, versionID)
if err != nil {
return nil, err
}
// Validate the request
if err := validators.ValidatePublishRequest(req, s.cfg); err != nil {
return nil, err
}
serverJSON := req
// Merge the request with the current server, preserving metadata
updatedServer := *currentServer // Copy the current server with all metadata
// Check for duplicate remote URLs
if err := s.validateNoDuplicateRemoteURLs(ctx, serverJSON); err != nil {
// Update only the user-modifiable fields from the request
updatedServer.Name = req.Name
updatedServer.Description = req.Description
updatedServer.Version = req.Version
updatedServer.Status = req.Status
updatedServer.Repository = req.Repository
updatedServer.Remotes = req.Remotes
updatedServer.Packages = req.Packages
// Update the UpdatedAt timestamp in metadata
if updatedServer.Meta != nil && updatedServer.Meta.Official != nil {
updatedServer.Meta.Official.UpdatedAt = time.Now()
}
// Check for duplicate remote URLs using the updated server
if err := s.validateNoDuplicateRemoteURLs(ctx, updatedServer); err != nil {
return nil, err
}
// Update server in database
serverRecord, err := s.db.UpdateServer(ctx, id, &serverJSON)
serverRecord, err := s.db.UpdateServer(ctx, versionID, &updatedServer)
if err != nil {
return nil, err
}

View file

@ -18,7 +18,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
"existing1": {
Name: "com.example/existing-server",
Description: "An existing server",
Version: "1.0.0",
Version: "1.0.0",
Remotes: []model.Transport{
{Type: "streamable-http", URL: "https://api.example.com/mcp"},
{Type: "sse", URL: "https://webhook.example.com/sse"},
@ -27,7 +27,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
"existing2": {
Name: "com.microsoft/another-server",
Description: "Another existing server",
Version: "1.0.0",
Version: "1.0.0",
Remotes: []model.Transport{
{Type: "streamable-http", URL: "https://api.microsoft.com/mcp"},
},
@ -55,8 +55,8 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
serverDetail: apiv0.ServerJSON{
Name: "com.example/new-server",
Description: "A new server with no remotes",
Version: "1.0.0",
Remotes: []model.Transport{},
Version: "1.0.0",
Remotes: []model.Transport{},
},
expectError: false,
},
@ -65,7 +65,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
serverDetail: apiv0.ServerJSON{
Name: "com.example/new-server",
Description: "A new server",
Version: "1.0.0",
Version: "1.0.0",
Remotes: []model.Transport{
{Type: "streamable-http", URL: "https://new.example.com/mcp"},
{Type: "sse", URL: "https://unique.example.com/sse"},
@ -78,7 +78,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
serverDetail: apiv0.ServerJSON{
Name: "com.example/new-server",
Description: "A new server with duplicate URL",
Version: "1.0.0",
Version: "1.0.0",
Remotes: []model.Transport{
{Type: "streamable-http", URL: "https://api.example.com/mcp"}, // This URL already exists
},
@ -91,7 +91,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
serverDetail: apiv0.ServerJSON{
Name: "com.example/existing-server", // Same name as existing
Description: "Updated existing server",
Version: "1.1.0",
Version: "1.1.0",
Remotes: []model.Transport{
{Type: "streamable-http", URL: "https://api.example.com/mcp"}, // Same URL as before
},
@ -116,3 +116,264 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
})
}
}
func TestGetByServerID(t *testing.T) {
memDB := database.NewMemoryDB()
service := NewRegistryService(memDB, &config.Config{EnableRegistryValidation: false})
// Publish multiple versions of the same server
server1, err := service.Publish(apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "Test server v1",
Version: "1.0.0",
})
assert.NoError(t, err)
_, err = service.Publish(apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "Test server v2",
Version: "2.0.0",
})
assert.NoError(t, err)
tests := []struct {
name string
serverID string
expectError bool
errorMsg string
checkResult func(*testing.T, *apiv0.ServerJSON)
}{
{
name: "get latest version by server ID",
serverID: server1.Meta.Official.ServerID,
expectError: false,
checkResult: func(t *testing.T, result *apiv0.ServerJSON) {
t.Helper()
assert.Equal(t, "2.0.0", result.Version) // Should get latest version
assert.Equal(t, "Test server v2", result.Description)
assert.True(t, result.Meta.Official.IsLatest)
},
},
{
name: "server not found",
serverID: "00000000-0000-0000-0000-000000000000",
expectError: true,
errorMsg: "record not found",
},
{
name: "invalid server ID format",
serverID: "invalid-uuid",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := service.GetByServerID(tt.serverID)
if tt.expectError {
assert.Error(t, err)
if tt.errorMsg != "" {
assert.Contains(t, err.Error(), tt.errorMsg)
}
assert.Nil(t, result)
} else {
assert.NoError(t, err)
assert.NotNil(t, result)
if tt.checkResult != nil {
tt.checkResult(t, result)
}
}
})
}
}
func TestGetByServerIDAndVersion(t *testing.T) {
memDB := database.NewMemoryDB()
service := NewRegistryService(memDB, &config.Config{EnableRegistryValidation: false})
// Publish multiple versions of the same server
server1, err := service.Publish(apiv0.ServerJSON{
Name: "com.example/versioned-server",
Description: "Versioned server v1",
Version: "1.0.0",
})
assert.NoError(t, err)
_, err = service.Publish(apiv0.ServerJSON{
Name: "com.example/versioned-server",
Description: "Versioned server v2",
Version: "2.0.0",
})
assert.NoError(t, err)
tests := []struct {
name string
serverID string
version string
expectError bool
errorMsg string
checkResult func(*testing.T, *apiv0.ServerJSON)
}{
{
name: "get specific version 1.0.0",
serverID: server1.Meta.Official.ServerID,
version: "1.0.0",
expectError: false,
checkResult: func(t *testing.T, result *apiv0.ServerJSON) {
t.Helper()
assert.Equal(t, "1.0.0", result.Version)
assert.Equal(t, "Versioned server v1", result.Description)
assert.False(t, result.Meta.Official.IsLatest)
},
},
{
name: "get specific version 2.0.0",
serverID: server1.Meta.Official.ServerID,
version: "2.0.0",
expectError: false,
checkResult: func(t *testing.T, result *apiv0.ServerJSON) {
t.Helper()
assert.Equal(t, "2.0.0", result.Version)
assert.Equal(t, "Versioned server v2", result.Description)
assert.True(t, result.Meta.Official.IsLatest)
},
},
{
name: "version not found",
serverID: server1.Meta.Official.ServerID,
version: "3.0.0",
expectError: true,
errorMsg: "record not found",
},
{
name: "server not found",
serverID: "00000000-0000-0000-0000-000000000000",
version: "1.0.0",
expectError: true,
errorMsg: "record not found",
},
{
name: "invalid server ID format",
serverID: "invalid-uuid",
version: "1.0.0",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := service.GetByServerIDAndVersion(tt.serverID, tt.version)
if tt.expectError {
assert.Error(t, err)
if tt.errorMsg != "" {
assert.Contains(t, err.Error(), tt.errorMsg)
}
assert.Nil(t, result)
} else {
assert.NoError(t, err)
assert.NotNil(t, result)
if tt.checkResult != nil {
tt.checkResult(t, result)
}
}
})
}
}
func TestGetAllVersionsByServerID(t *testing.T) {
memDB := database.NewMemoryDB()
service := NewRegistryService(memDB, &config.Config{EnableRegistryValidation: false})
// Publish multiple versions of the same server
server1, err := service.Publish(apiv0.ServerJSON{
Name: "com.example/multi-version-server",
Description: "Multi-version server v1",
Version: "1.0.0",
})
assert.NoError(t, err)
_, err = service.Publish(apiv0.ServerJSON{
Name: "com.example/multi-version-server",
Description: "Multi-version server v2",
Version: "2.0.0",
})
assert.NoError(t, err)
_, err = service.Publish(apiv0.ServerJSON{
Name: "com.example/multi-version-server",
Description: "Multi-version server v2.1",
Version: "2.1.0",
})
assert.NoError(t, err)
tests := []struct {
name string
serverID string
expectError bool
errorMsg string
checkResult func(*testing.T, []apiv0.ServerJSON)
}{
{
name: "get all versions of server",
serverID: server1.Meta.Official.ServerID,
expectError: false,
checkResult: func(t *testing.T, result []apiv0.ServerJSON) {
t.Helper()
assert.Len(t, result, 3)
// Collect versions
versions := make([]string, 0, len(result))
latestCount := 0
for _, server := range result {
versions = append(versions, server.Version)
assert.Equal(t, server1.Meta.Official.ServerID, server.Meta.Official.ServerID)
assert.Equal(t, "com.example/multi-version-server", server.Name)
if server.Meta.Official.IsLatest {
latestCount++
}
}
// Verify all versions are present
assert.Contains(t, versions, "1.0.0")
assert.Contains(t, versions, "2.0.0")
assert.Contains(t, versions, "2.1.0")
// Only one should be marked as latest
assert.Equal(t, 1, latestCount)
},
},
{
name: "server not found",
serverID: "00000000-0000-0000-0000-000000000000",
expectError: true,
errorMsg: "record not found",
},
{
name: "invalid server ID format",
serverID: "invalid-uuid",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := service.GetAllVersionsByServerID(tt.serverID)
if tt.expectError {
assert.Error(t, err)
if tt.errorMsg != "" {
assert.Contains(t, err.Error(), tt.errorMsg)
}
assert.Empty(t, result)
} else {
assert.NoError(t, err)
assert.NotEmpty(t, result)
if tt.checkResult != nil {
tt.checkResult(t, result)
}
}
})
}
}

View file

@ -9,8 +9,14 @@ import (
type RegistryService interface {
// Retrieve all servers with optional filtering
List(filter *database.ServerFilter, cursor string, limit int) ([]apiv0.ServerJSON, string, error)
// Retrieve a single server by registry metadata ID
GetByID(id string) (*apiv0.ServerJSON, error)
// Retrieve a single server by registry metadata version ID
GetByVersionID(versionID string) (*apiv0.ServerJSON, error)
// Retrieve latest version of a server by server ID
GetByServerID(serverID string) (*apiv0.ServerJSON, error)
// Retrieve specific version of a server by server ID and version
GetByServerIDAndVersion(serverID string, version string) (*apiv0.ServerJSON, error)
// Retrieve all versions of a server by server ID
GetAllVersionsByServerID(serverID string) ([]apiv0.ServerJSON, error)
// Publish a server
Publish(req apiv0.ServerJSON) (*apiv0.ServerJSON, error)
// Update an existing server

View file

@ -15,7 +15,7 @@ import (
func ValidateMCPB(ctx context.Context, pkg model.Package, _ string) error {
// MCPB packages must include a file hash for integrity verification
if pkg.FileSHA256 == "" {
return fmt.Errorf("MCPB package must include a file_sha256 hash for integrity verification")
return fmt.Errorf("MCPB package must include a fileSha256 hash for integrity verification")
}
err := validateMCPBUrl(pkg.Identifier)

View file

@ -40,7 +40,7 @@ func TestValidateMCPB(t *testing.T) {
serverName: "com.example/test",
fileSHA256: "",
expectError: true,
errorMessage: "must include a file_sha256 hash for integrity verification",
errorMessage: "must include a fileSha256 hash for integrity verification",
},
{
name: "non-existent .mcpb package should fail accessibility check",

View file

@ -118,17 +118,17 @@ func validateWebsiteURL(websiteURL string) error {
// Parse the URL to ensure it's valid
parsedURL, err := url.Parse(websiteURL)
if err != nil {
return fmt.Errorf("invalid website URL: %w", err)
return fmt.Errorf("invalid websiteUrl: %w", err)
}
// Ensure it's an absolute URL with valid scheme
if !parsedURL.IsAbs() {
return fmt.Errorf("website URL must be absolute (include scheme): %s", websiteURL)
return fmt.Errorf("websiteUrl must be absolute (include scheme): %s", websiteURL)
}
// Only allow HTTP/HTTPS schemes for security
if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
return fmt.Errorf("website URL must use http or https scheme: %s", websiteURL)
return fmt.Errorf("websiteUrl must use http or https scheme: %s", websiteURL)
}
return nil
@ -438,7 +438,7 @@ func validateWebsiteURLNamespaceMatch(serverJSON apiv0.ServerJSON) error {
namespace := serverJSON.Name
if err := validateRemoteURLMatchesNamespace(serverJSON.WebsiteURL, namespace); err != nil {
return fmt.Errorf("website URL %s does not match namespace %s: %w", serverJSON.WebsiteURL, namespace, err)
return fmt.Errorf("websiteUrl %s does not match namespace %s: %w", serverJSON.WebsiteURL, namespace, err)
}
return nil

View file

@ -4,11 +4,12 @@ import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/modelcontextprotocol/registry/internal/config"
"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"
)
func TestValidate(t *testing.T) {
@ -345,7 +346,7 @@ func TestValidate(t *testing.T) {
expectedError: validators.ErrInvalidSubfolderPath.Error(),
},
{
name: "server with valid website URL",
name: "server with valid websiteUrl",
serverDetail: apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
@ -359,7 +360,7 @@ func TestValidate(t *testing.T) {
expectedError: "",
},
{
name: "server with invalid website URL - no scheme",
name: "server with invalid websiteUrl - no scheme",
serverDetail: apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
@ -370,10 +371,10 @@ func TestValidate(t *testing.T) {
Version: "1.0.0",
WebsiteURL: "example.com/docs",
},
expectedError: "website URL must be absolute (include scheme): example.com/docs",
expectedError: "websiteUrl must be absolute (include scheme): example.com/docs",
},
{
name: "server with invalid website URL - invalid scheme",
name: "server with invalid websiteUrl - invalid scheme",
serverDetail: apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
@ -384,10 +385,10 @@ func TestValidate(t *testing.T) {
Version: "1.0.0",
WebsiteURL: "ftp://example.com/docs",
},
expectedError: "website URL must use http or https scheme: ftp://example.com/docs",
expectedError: "websiteUrl must use http or https scheme: ftp://example.com/docs",
},
{
name: "server with malformed website URL",
name: "server with malformed websiteUrl",
serverDetail: apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
@ -398,10 +399,10 @@ func TestValidate(t *testing.T) {
Version: "1.0.0",
WebsiteURL: "ht tp://example.com/docs",
},
expectedError: "invalid website URL:",
expectedError: "invalid websiteUrl:",
},
{
name: "server with website URL that matches namespace domain",
name: "server with websiteUrl that matches namespace domain",
serverDetail: apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
@ -415,7 +416,7 @@ func TestValidate(t *testing.T) {
expectedError: "",
},
{
name: "server with website URL subdomain that matches namespace",
name: "server with websiteUrl subdomain that matches namespace",
serverDetail: apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
@ -429,7 +430,7 @@ func TestValidate(t *testing.T) {
expectedError: "",
},
{
name: "server with website URL that does not match namespace",
name: "server with websiteUrl that does not match namespace",
serverDetail: apiv0.ServerJSON{
Name: "com.example/test-server",
Description: "A test server",
@ -440,7 +441,7 @@ func TestValidate(t *testing.T) {
Version: "1.0.0",
WebsiteURL: "https://different.com/docs",
},
expectedError: "website URL https://different.com/docs does not match namespace com.example/test-server",
expectedError: "websiteUrl https://different.com/docs does not match namespace com.example/test-server",
},
{
name: "package with spaces in name",