Publisher-managed "deleted" support (#893)
(Updated auto-generated PR description from @tadasant / Claude on Feb 22, 2026) ## Motivation and Context Fixes #637 Server lifecycle management (deprecation and yanking) is a standard requirement for package registries. Use cases like rebranding, security vulnerabilities, and end-of-life servers demand the ability to mark servers as deprecated or deleted, with optional messaging to guide consumers toward alternatives. ## Changes ### New API endpoints - **`PATCH /v0/servers/{serverName}/versions/{version}/status`** — Update the lifecycle status of a single server version - **`PATCH /v0/servers/{serverName}/status`** — Update the lifecycle status of all versions of a server in a single transaction Both endpoints accept: ```json { "status": "active|deprecated|deleted", "statusMessage": "Optional message (max 500 chars) explaining the change" } ``` ### New CLI command - **`mcp-publisher status <serverName> [version]`** — Update server lifecycle status from the command line - `--status` (required): `active`, `deprecated`, or `deleted` - `--message`: Optional status message - `--all-versions`: Apply to all versions of the server (replaces the `<version>` argument) ### API response changes `RegistryExtensions` now includes two new fields: - `statusChangedAt` — Timestamp of the last status change - `statusMessage` — Optional free-form message (e.g., deprecation reason, migration guidance) ### List endpoint changes - New `include_deleted` query parameter on `GET /v0/servers` — defaults to `false`, hiding deleted servers from listings - When `updated_since` is provided, `include_deleted` is automatically set to `true` for incremental sync ### Database - Migration `013_add_status_fields.sql`: Adds `status_changed_at` (NOT NULL, initialized from `published_at`) and `status_message` columns to the `servers` table ### Design decisions (from review discussion) - **Dedicated status endpoints** rather than overloading the existing edit endpoint - **Bidirectional status transitions** — all transitions between `active`, `deprecated`, and `deleted` are allowed - **`statusMessage` as free-form text** — no structured `nextName` or `alternativeUrl` fields (per maintainer feedback, to avoid complexity around chaining, trust transfer, etc.) - **Publish permission** grants status change access (not limited to admin/edit) - **Status message auto-cleared** when transitioning back to `active` Good, now I have the full picture. Here's the addendum: ### Consumer-facing API changes The new status fields live inside `_meta["io.modelcontextprotocol.registry/official"]` on every `ServerResponse`. This is the existing `RegistryExtensions` object — two new fields are added alongside the existing ones: **Before:** ```json { "server": { "name": "com.example/my-server", "...": "..." }, "_meta": { "io.modelcontextprotocol.registry/official": { "status": "active", "publishedAt": "2025-06-01T00:00:00Z", "updatedAt": "2025-06-15T00:00:00Z", "isLatest": true } } } ``` **After:** ```json { "server": { "name": "com.example/my-server", "...": "..." }, "_meta": { "io.modelcontextprotocol.registry/official": { "status": "deprecated", "statusChangedAt": "2026-02-01T12:00:00Z", "statusMessage": "Deprecated in favor of com.example/my-server-v2", "publishedAt": "2025-06-01T00:00:00Z", "updatedAt": "2026-02-01T12:00:00Z", "isLatest": true } } } ``` | New field | Type | Present when | |-----------|------|-------------| | `statusChangedAt` | `string` (RFC3339) | Always — initialized to `publishedAt` for existing records | | `statusMessage` | `string` (max 500 chars) | Only when set — `null`/omitted for active servers (auto-cleared on transition to active) | These fields appear on **every endpoint that returns a `ServerResponse`**: `GET /v0/servers`, `GET /v0/servers/{name}`, `GET /v0/servers/{name}/versions/{version}`, and the new PATCH status endpoints. ### List endpoint filtering `GET /v0/servers` gains an `include_deleted` query parameter: | Scenario | Behavior | |----------|----------| | No `include_deleted` param | Deleted servers hidden (default `false`) | | `include_deleted=true` | Deleted servers included in results | | `updated_since` provided | `include_deleted` forced to `true` for incremental sync | ## How Has This Been Tested? - Unit tests for status handler (`status_test.go`) covering status transitions, permission checks, validation errors, and the all-versions endpoint - Unit tests for the CLI command (`status_test.go`) - Integration with existing server/edit handler tests - Database layer tests for the new status update and query methods - Tested locally with `make dev-compose` ## Types of changes - [x] New feature (non-breaking change which adds functionality) ## Checklist - [x] I have read the [MCP Documentation](https://modelcontextprotocol.io) - [x] My code follows the repository's style guidelines - [x] New and existing tests pass locally - [x] I have added appropriate error handling - [x] I have added or updated documentation as needed ## Open items from review - [ ] `include_deleted` silent override: When `updated_since` is provided and `include_deleted=false` is explicitly passed, should return a 400 error rather than silently overriding ([thread](https://github.com/modelcontextprotocol/registry/pull/893#discussion_r2100879360)) — agreed upon but may not yet be implemented
This commit is contained in:
parent
01e4e2b09e
commit
bb84ea69e8
15 changed files with 4153 additions and 474 deletions
|
|
@ -8,13 +8,13 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
"github.com/modelcontextprotocol/registry/internal/validators"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// EditServerInput represents the input for editing a server
|
||||
|
|
@ -22,7 +22,6 @@ type EditServerInput struct {
|
|||
Authorization string `header:"Authorization" doc:"Registry JWT token with edit permissions" required:"true"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded version to edit" example:"1.0.0"`
|
||||
Status string `query:"status" doc:"New status for the server (active, deprecated, deleted)" required:"false" enum:"active,deprecated,deleted"`
|
||||
Body apiv0.ServerJSON `body:""`
|
||||
}
|
||||
|
||||
|
|
@ -36,8 +35,8 @@ func RegisterEditEndpoints(api huma.API, pathPrefix string, registry service.Reg
|
|||
Method: http.MethodPut,
|
||||
Path: pathPrefix + "/servers/{serverName}/versions/{version}",
|
||||
Summary: "Edit MCP server",
|
||||
Description: "Update a specific version of an existing MCP server (admin only).",
|
||||
Tags: []string{"admin"},
|
||||
Description: "Update the configuration of a specific version of an existing MCP server. Requires edit permission for the server. Use PATCH /servers/{serverName}/versions/{version}/status to update status metadata.",
|
||||
Tags: []string{"servers"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
|
|
@ -69,7 +68,8 @@ func RegisterEditEndpoints(api huma.API, pathPrefix string, registry service.Reg
|
|||
}
|
||||
|
||||
// Get current server to check permissions against existing name
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
// Deleted servers return 404 - restore via status endpoint first
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version, false)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
@ -98,28 +98,7 @@ func RegisterEditEndpoints(api huma.API, pathPrefix string, registry service.Reg
|
|||
return nil, huma.Error422UnprocessableEntity("Failed to edit server, invalid schema: call /validate for details")
|
||||
}
|
||||
|
||||
// Handle status changes with proper permission validation
|
||||
if input.Status != "" {
|
||||
newStatus := model.Status(input.Status)
|
||||
|
||||
// Prevent undeleting servers - once deleted, they stay deleted
|
||||
if currentServer.Meta.Official != nil &&
|
||||
currentServer.Meta.Official.Status == model.StatusDeleted &&
|
||||
newStatus != model.StatusDeleted {
|
||||
return nil, huma.Error400BadRequest("Cannot change status of deleted server. Deleted servers cannot be undeleted.")
|
||||
}
|
||||
|
||||
// For now, only allow status changes for admins
|
||||
// Future: Implement logic to allow server authors to change active <-> deprecated
|
||||
// but only admins can set to deleted
|
||||
}
|
||||
|
||||
// Update the server using the service
|
||||
var statusPtr *string
|
||||
if input.Status != "" {
|
||||
statusPtr = &input.Status
|
||||
}
|
||||
updatedServer, err := registry.UpdateServer(ctx, serverName, version, &input.Body, statusPtr)
|
||||
updatedServer, err := registry.UpdateServer(ctx, serverName, version, &input.Body, nil)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
|
|||
|
|
@ -71,25 +71,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Create a deleted server for undelete testing
|
||||
deletedServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Server that was deleted",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/deleted-server",
|
||||
Source: "github",
|
||||
ID: "testuser/deleted-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), deletedServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set the server to deleted status
|
||||
_, err = registryService.UpdateServer(context.Background(), deletedServer.Name, deletedServer.Version, deletedServer, stringPtr(string(model.StatusDeleted)))
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create a server with build metadata for URL encoding test
|
||||
buildMetadataServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
|
|
@ -112,7 +93,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody apiv0.ServerJSON
|
||||
statusParam string
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
|
|
@ -148,31 +128,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
assert.NotNil(t, resp.Meta.Official)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful edit with status change",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/editable-server",
|
||||
Description: "Server with status change",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
statusParam: "deprecated",
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "Server with status change", resp.Server.Description)
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
serverName: "io.github.testuser/editable-server",
|
||||
|
|
@ -310,27 +265,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Version in request body must match URL path parameter",
|
||||
},
|
||||
{
|
||||
name: "attempt to undelete server should fail",
|
||||
serverName: "io.github.testuser/deleted-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Trying to undelete server",
|
||||
Version: "1.0.0",
|
||||
},
|
||||
statusParam: "active", // Trying to change from deleted to active
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "Cannot change status of deleted server",
|
||||
},
|
||||
{
|
||||
name: "successful edit of version with build metadata (URL encoded)",
|
||||
serverName: "io.github.testuser/build-metadata-server",
|
||||
|
|
@ -381,9 +315,6 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
encodedServerName := url.PathEscape(tc.serverName)
|
||||
encodedVersion := url.PathEscape(tc.version)
|
||||
requestURL := "/v0/servers/" + encodedServerName + "/versions/" + encodedVersion
|
||||
if tc.statusParam != "" {
|
||||
requestURL += "?status=" + tc.statusParam
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
|
@ -404,6 +335,9 @@ func TestEditServerEndpoint(t *testing.T) {
|
|||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check response
|
||||
if tc.expectedStatus != w.Code {
|
||||
t.Logf("Response body: %s", w.Body.String())
|
||||
}
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
if tc.expectedError != "" {
|
||||
|
|
@ -437,12 +371,10 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
testServers := []struct {
|
||||
name string
|
||||
version string
|
||||
status model.Status
|
||||
}{
|
||||
{"com.example/active-server", "1.0.0", model.StatusActive},
|
||||
{"com.example/deprecated-server", "1.0.0", model.StatusDeprecated},
|
||||
{"com.example/multi-version-server", "1.0.0", model.StatusActive},
|
||||
{"com.example/multi-version-server", "2.0.0", model.StatusActive},
|
||||
{"com.example/active-server", "1.0.0"},
|
||||
{"com.example/multi-version-server", "1.0.0"},
|
||||
{"com.example/multi-version-server", "2.0.0"},
|
||||
}
|
||||
|
||||
for _, server := range testServers {
|
||||
|
|
@ -453,17 +385,6 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
Version: server.version,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set specific status if not active
|
||||
if server.status != model.StatusActive {
|
||||
_, err = registryService.UpdateServer(context.Background(), server.name, server.version, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: server.name,
|
||||
Description: "Test server for editing",
|
||||
Version: server.version,
|
||||
}, stringPtr(string(server.status)))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Create API
|
||||
|
|
@ -471,95 +392,6 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterEditEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
t.Run("status transitions", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
fromStatus string
|
||||
toStatus string
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
}{
|
||||
{
|
||||
name: "active to deprecated",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "deprecated",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "deprecated to active",
|
||||
serverName: "com.example/deprecated-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "active",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "active to deleted",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "deleted",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "invalid status",
|
||||
serverName: "com.example/active-server",
|
||||
version: "1.0.0",
|
||||
toStatus: "invalid_status",
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "validation failed",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: tt.serverName,
|
||||
Description: "Status transition test",
|
||||
Version: tt.version,
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(tt.serverName)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/" + tt.version + "?status=" + tt.toStatus
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
if tt.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tt.expectedError)
|
||||
}
|
||||
|
||||
if tt.expectedStatus == http.StatusOK {
|
||||
var response apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.Status(tt.toStatus), response.Meta.Official.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("URL encoding edge cases", func(t *testing.T) {
|
||||
// Create server with special characters
|
||||
specialServerName := "io.dots.and-dashes/server_with_underscores"
|
||||
|
|
@ -651,13 +483,70 @@ func TestEditServerEndpointEdgeCases(t *testing.T) {
|
|||
assert.Equal(t, "1.0.0", response.Server.Version)
|
||||
|
||||
// Verify the other version wasn't affected
|
||||
otherVersion, err := registryService.GetServerByNameAndVersion(context.Background(), "com.example/multi-version-server", "2.0.0")
|
||||
otherVersion, err := registryService.GetServerByNameAndVersion(context.Background(), "com.example/multi-version-server", "2.0.0", false)
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, "Updated v1.0.0 specifically", otherVersion.Server.Description)
|
||||
})
|
||||
}
|
||||
|
||||
// Helper function
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
t.Run("edit preserves status metadata", func(t *testing.T) {
|
||||
// Create a server and set it to deprecated using the service directly
|
||||
deprecatedServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/deprecated-for-edit-test",
|
||||
Description: "Server to test edit preserves status",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
_, err := registryService.CreateServer(context.Background(), deprecatedServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set to deprecated status using UpdateServerStatus
|
||||
statusMsg := "This server is deprecated"
|
||||
_, err = registryService.UpdateServerStatus(context.Background(), deprecatedServer.Name, deprecatedServer.Version, &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeprecated,
|
||||
StatusMessage: &statusMsg,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Now edit the server description
|
||||
requestBody := apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/deprecated-for-edit-test",
|
||||
Description: "Updated description but status should remain deprecated",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape("com.example/deprecated-for-edit-test")
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPut, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var response apiv0.ServerResponse
|
||||
err = json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "Updated description but status should remain deprecated", response.Server.Description)
|
||||
// Status should still be deprecated
|
||||
assert.Equal(t, model.StatusDeprecated, response.Meta.Official.Status)
|
||||
// Status message should be preserved
|
||||
assert.NotNil(t, response.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "This server is deprecated", *response.Meta.Official.StatusMessage)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
|
|
@ -16,13 +17,49 @@ import (
|
|||
|
||||
const errRecordNotFound = "record not found"
|
||||
|
||||
// OptionalBool tracks whether a bool query parameter was explicitly set
|
||||
type OptionalBool struct {
|
||||
Value bool
|
||||
IsSet bool
|
||||
}
|
||||
|
||||
// Schema implements huma.SchemaProvider - returns schema for the wrapped type
|
||||
func (o OptionalBool) Schema(r huma.Registry) *huma.Schema {
|
||||
return huma.SchemaFromType(r, reflect.TypeOf(o.Value))
|
||||
}
|
||||
|
||||
// Receiver implements huma.ParamWrapper - exposes wrapped value to receive parsed value
|
||||
func (o *OptionalBool) Receiver() reflect.Value {
|
||||
return reflect.ValueOf(o).Elem().Field(0)
|
||||
}
|
||||
|
||||
// OnParamSet implements huma.ParamReactor - tracks whether parameter was set in request
|
||||
func (o *OptionalBool) OnParamSet(isSet bool, _ any) {
|
||||
o.IsSet = isSet
|
||||
}
|
||||
|
||||
// resolveIncludeDeleted handles the include_deleted parameter logic for list endpoints
|
||||
// Returns the resolved value and an error if include_deleted=false conflicts with updated_since
|
||||
func resolveIncludeDeleted(includeDeleted OptionalBool, hasUpdatedSince bool) (bool, error) {
|
||||
if hasUpdatedSince {
|
||||
// When updated_since is provided, include_deleted must be true for incremental sync
|
||||
if includeDeleted.IsSet && !includeDeleted.Value {
|
||||
return false, huma.Error400BadRequest("Cannot set include_deleted=false when using updated_since (incremental sync requires deleted servers)")
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
// Use provided value, defaults to false if not set
|
||||
return includeDeleted.Value, nil
|
||||
}
|
||||
|
||||
// ListServersInput represents the input for listing servers
|
||||
type ListServersInput struct {
|
||||
Cursor string `query:"cursor" doc:"Pagination cursor" required:"false" example:"server-cursor-123"`
|
||||
Limit int `query:"limit" doc:"Number of items per page" default:"30" minimum:"1" maximum:"100" example:"50"`
|
||||
UpdatedSince string `query:"updated_since" doc:"Filter servers updated since timestamp (RFC3339 datetime)" required:"false" example:"2025-08-07T13:15:04.280Z"`
|
||||
Search string `query:"search" doc:"Search servers by name (substring match)" required:"false" example:"filesystem"`
|
||||
Version string `query:"version" doc:"Filter by version ('latest' for latest version, or an exact version like '1.2.3')" required:"false" example:"latest"`
|
||||
Cursor string `query:"cursor" doc:"Pagination cursor" required:"false" example:"server-cursor-123"`
|
||||
Limit int `query:"limit" doc:"Number of items per page" default:"30" minimum:"1" maximum:"100" example:"50"`
|
||||
UpdatedSince string `query:"updated_since" doc:"Filter servers updated since timestamp (RFC3339 datetime)" required:"false" example:"2025-08-07T13:15:04.280Z"`
|
||||
Search string `query:"search" doc:"Search servers by name (substring match)" required:"false" example:"filesystem"`
|
||||
Version string `query:"version" doc:"Filter by version ('latest' for latest version, or an exact version like '1.2.3')" required:"false" example:"latest"`
|
||||
IncludeDeleted OptionalBool `query:"include_deleted" doc:"Include deleted servers in results (default: false, but always true when updated_since is provided)" required:"false"`
|
||||
}
|
||||
|
||||
// ServerDetailInput represents the input for getting server details
|
||||
|
|
@ -32,13 +69,15 @@ type ServerDetailInput struct {
|
|||
|
||||
// ServerVersionDetailInput represents the input for getting a specific version
|
||||
type ServerVersionDetailInput struct {
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded server version" example:"1.0.0"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded server version" example:"1.0.0"`
|
||||
IncludeDeleted bool `query:"include_deleted" doc:"Include deleted servers in results (default: false)" required:"false" default:"false"`
|
||||
}
|
||||
|
||||
// ServerVersionsInput represents the input for listing all versions of a server
|
||||
type ServerVersionsInput struct {
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
IncludeDeleted bool `query:"include_deleted" doc:"Include deleted servers in results (default: false)" required:"false" default:"false"`
|
||||
}
|
||||
|
||||
// RegisterServersEndpoints registers all server-related endpoints with a custom path prefix
|
||||
|
|
@ -82,6 +121,13 @@ func RegisterServersEndpoints(api huma.API, pathPrefix string, registry service.
|
|||
}
|
||||
}
|
||||
|
||||
// Handle include_deleted parameter
|
||||
includeDeleted, err := resolveIncludeDeleted(input.IncludeDeleted, filter.UpdatedSince != nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.IncludeDeleted = &includeDeleted
|
||||
|
||||
// Get paginated results with filtering
|
||||
servers, nextCursor, err := registry.ListServers(ctx, filter, input.Cursor, input.Limit)
|
||||
if err != nil {
|
||||
|
|
@ -129,9 +175,9 @@ func RegisterServersEndpoints(api huma.API, pathPrefix string, registry service.
|
|||
var serverResponse *apiv0.ServerResponse
|
||||
// Handle "latest" as a special version
|
||||
if version == "latest" {
|
||||
serverResponse, err = registry.GetServerByName(ctx, serverName)
|
||||
serverResponse, err = registry.GetServerByName(ctx, serverName, input.IncludeDeleted)
|
||||
} else {
|
||||
serverResponse, err = registry.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
serverResponse, err = registry.GetServerByNameAndVersion(ctx, serverName, version, input.IncludeDeleted)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
|
|
@ -162,7 +208,7 @@ func RegisterServersEndpoints(api huma.API, pathPrefix string, registry service.
|
|||
}
|
||||
|
||||
// Get all versions for this server
|
||||
servers, err := registry.GetAllVersionsByServerName(ctx, serverName)
|
||||
servers, err := registry.GetAllVersionsByServerName(ctx, serverName, input.IncludeDeleted)
|
||||
if err != nil {
|
||||
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
|
|
|
|||
|
|
@ -392,6 +392,122 @@ func TestGetAllVersionsEndpoint(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestListServersDeletedFiltering(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
||||
// Setup test data: 2 active servers and 1 deleted server
|
||||
_, err := registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/active-server-1",
|
||||
Description: "Active server 1",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/active-server-2",
|
||||
Description: "Active server 2",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/deleted-server",
|
||||
Description: "Deleted server",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete the third server
|
||||
_, err = registryService.UpdateServerStatus(ctx, "com.example/deleted-server", "1.0.0", &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterServersEndpoints(api, "/v0", registryService)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
queryParams string
|
||||
expectedStatus int
|
||||
expectedCount int
|
||||
checkDeleted bool // whether deleted server should be in results
|
||||
}{
|
||||
{
|
||||
name: "default excludes deleted servers",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 2,
|
||||
checkDeleted: false,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=false excludes deleted servers",
|
||||
queryParams: "?include_deleted=false",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 2,
|
||||
checkDeleted: false,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=true includes deleted servers",
|
||||
queryParams: "?include_deleted=true",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 3,
|
||||
checkDeleted: true,
|
||||
},
|
||||
{
|
||||
name: "updated_since always includes deleted servers",
|
||||
queryParams: "?updated_since=1990-01-01T00:00:00Z",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 3,
|
||||
checkDeleted: true,
|
||||
},
|
||||
{
|
||||
name: "updated_since with include_deleted=false returns error",
|
||||
queryParams: "?updated_since=1990-01-01T00:00:00Z&include_deleted=false",
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedCount: 0,
|
||||
checkDeleted: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/servers"+tt.queryParams, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
// Skip response body checks for error responses
|
||||
if tt.expectedStatus != http.StatusOK {
|
||||
return
|
||||
}
|
||||
|
||||
var resp apiv0.ServerListResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, resp.Servers, tt.expectedCount)
|
||||
|
||||
// Check if deleted server is in results
|
||||
hasDeleted := false
|
||||
for _, server := range resp.Servers {
|
||||
if server.Server.Name == "com.example/deleted-server" {
|
||||
hasDeleted = true
|
||||
assert.Equal(t, model.StatusDeleted, server.Meta.Official.Status)
|
||||
}
|
||||
}
|
||||
assert.Equal(t, tt.checkDeleted, hasDeleted, "Deleted server presence mismatch")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServersEndpointEdgeCases(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
|
@ -518,3 +634,137 @@ func TestServersEndpointEdgeCases(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestIncludeDeletedOnDetailEndpoints(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), config.NewConfig())
|
||||
|
||||
serverName := "com.example/deleted-detail-test"
|
||||
|
||||
// Create server with multiple versions
|
||||
_, err := registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: serverName,
|
||||
Description: "Test server v1",
|
||||
Version: "1.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = registryService.CreateServer(ctx, &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: serverName,
|
||||
Description: "Test server v2",
|
||||
Version: "2.0.0",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete version 1.0.0
|
||||
_, err = registryService.UpdateServerStatus(ctx, serverName, "1.0.0", &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterServersEndpoints(api, "/v0", registryService)
|
||||
|
||||
encodedName := url.PathEscape(serverName)
|
||||
|
||||
t.Run("detail endpoint", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
version string
|
||||
queryParams string
|
||||
expectedStatus int
|
||||
}{
|
||||
{
|
||||
name: "deleted version without include_deleted returns 404",
|
||||
version: "1.0.0",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "deleted version with include_deleted=false returns 404",
|
||||
version: "1.0.0",
|
||||
queryParams: "?include_deleted=false",
|
||||
expectedStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "deleted version with include_deleted=true returns 200",
|
||||
version: "1.0.0",
|
||||
queryParams: "?include_deleted=true",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "active version without include_deleted returns 200",
|
||||
version: "2.0.0",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusOK,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
encodedVersion := url.PathEscape(tt.version)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/servers/"+encodedName+"/versions/"+encodedVersion+tt.queryParams, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
if tt.expectedStatus == http.StatusOK {
|
||||
var resp apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, tt.version, resp.Server.Version)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("version history endpoint", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
queryParams string
|
||||
expectedStatus int
|
||||
expectedCount int
|
||||
}{
|
||||
{
|
||||
name: "without include_deleted excludes deleted versions",
|
||||
queryParams: "",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 1,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=false excludes deleted versions",
|
||||
queryParams: "?include_deleted=false",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 1,
|
||||
},
|
||||
{
|
||||
name: "include_deleted=true includes deleted versions",
|
||||
queryParams: "?include_deleted=true",
|
||||
expectedStatus: http.StatusOK,
|
||||
expectedCount: 2,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest(http.MethodGet, "/v0/servers/"+encodedName+"/versions"+tt.queryParams, nil)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, tt.expectedStatus, w.Code)
|
||||
|
||||
var resp apiv0.ServerListResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&resp)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, resp.Servers, tt.expectedCount)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
299
internal/api/handlers/v0/status.go
Normal file
299
internal/api/handlers/v0/status.go
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
package v0
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// UpdateServerStatusBody represents the request body for updating server status
|
||||
type UpdateServerStatusBody struct {
|
||||
Status string `json:"status" required:"true" enum:"active,deprecated,deleted" doc:"New server lifecycle status"`
|
||||
StatusMessage *string `json:"statusMessage,omitempty" maxLength:"500" doc:"Optional message explaining the status change (e.g., reason for deprecation)"`
|
||||
}
|
||||
|
||||
// UpdateServerStatusInput represents the input for updating server status
|
||||
type UpdateServerStatusInput struct {
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token with publish or edit permissions" required:"true"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Version string `path:"version" doc:"URL-encoded version to update" example:"1.0.0"`
|
||||
Body UpdateServerStatusBody `body:""`
|
||||
}
|
||||
|
||||
// validateStatusTransition validates if the status transition is allowed
|
||||
// Returns nil if status or message differs from current (something to update)
|
||||
// Returns error if nothing changes (no-op) or if status transition is invalid
|
||||
func validateStatusTransition(currentServer *apiv0.ServerResponse, newStatus model.Status, body UpdateServerStatusBody) error {
|
||||
// Validate newStatus is a valid value
|
||||
validStatuses := map[model.Status]bool{
|
||||
model.StatusActive: true,
|
||||
model.StatusDeprecated: true,
|
||||
model.StatusDeleted: true,
|
||||
}
|
||||
if !validStatuses[newStatus] {
|
||||
return huma.Error400BadRequest(fmt.Sprintf("Invalid status: %s. Must be one of: active, deprecated, deleted", newStatus))
|
||||
}
|
||||
|
||||
// Reject status_message when setting status to active
|
||||
if newStatus == model.StatusActive && body.StatusMessage != nil {
|
||||
return huma.Error400BadRequest("status_message cannot be provided when setting status to active")
|
||||
}
|
||||
|
||||
if currentServer.Meta.Official == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
currentStatus := currentServer.Meta.Official.Status
|
||||
currentMessage := currentServer.Meta.Official.StatusMessage
|
||||
newMessage := body.StatusMessage
|
||||
|
||||
statusChanges := currentStatus != newStatus
|
||||
messageChanges := (currentMessage == nil) != (newMessage == nil) ||
|
||||
(currentMessage != nil && newMessage != nil && *currentMessage != *newMessage)
|
||||
|
||||
// Valid if either status or message changes
|
||||
if statusChanges || messageChanges {
|
||||
return nil
|
||||
}
|
||||
|
||||
return huma.Error400BadRequest("No changes to apply: status and message are already set to the provided values")
|
||||
}
|
||||
|
||||
// RegisterStatusEndpoints registers the status update endpoint with a custom path prefix
|
||||
func RegisterStatusEndpoints(api huma.API, pathPrefix string, registry service.RegistryService, cfg *config.Config) {
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
|
||||
// Update server status endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "update-server-status" + strings.ReplaceAll(pathPrefix, "/", "-"),
|
||||
Method: http.MethodPatch,
|
||||
Path: pathPrefix + "/servers/{serverName}/versions/{version}/status",
|
||||
Summary: "Update MCP server status",
|
||||
Description: "Update the status metadata of a specific version of an MCP server. Requires publish or edit permission for the server. This endpoint allows changing status and status message without requiring the full server configuration.",
|
||||
Tags: []string{"servers"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *UpdateServerStatusInput) (*Response[apiv0.ServerResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
if len(authHeader) < len(bearerPrefix) || !strings.EqualFold(authHeader[:len(bearerPrefix)], bearerPrefix) {
|
||||
return nil, huma.Error401Unauthorized("Invalid Authorization header format. Expected 'Bearer <token>'")
|
||||
}
|
||||
token := authHeader[len(bearerPrefix):]
|
||||
|
||||
// Validate Registry JWT token
|
||||
claims, err := jwtManager.ValidateToken(ctx, token)
|
||||
if err != nil {
|
||||
return nil, huma.Error401Unauthorized("Invalid or expired Registry JWT token", err)
|
||||
}
|
||||
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// URL-decode the version
|
||||
version, err := url.PathUnescape(input.Version)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid version encoding", err)
|
||||
}
|
||||
|
||||
newStatus := model.Status(input.Body.Status)
|
||||
|
||||
// Get the server and verify it exists
|
||||
// Include deleted servers since we need to be able to restore them
|
||||
currentServer, err := registry.GetServerByNameAndVersion(ctx, serverName, version, true)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server version not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server", err)
|
||||
}
|
||||
|
||||
// Verify publish or edit permissions for this server
|
||||
hasPublish := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionPublish, claims.Permissions)
|
||||
hasEdit := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionEdit, claims.Permissions)
|
||||
if !hasPublish && !hasEdit {
|
||||
return nil, huma.Error403Forbidden("You do not have publish or edit permissions for this server")
|
||||
}
|
||||
|
||||
// Validate status transition is allowed
|
||||
if err := validateStatusTransition(currentServer, newStatus, input.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Build status change request
|
||||
statusChange := buildStatusChangeRequestFromBody(input.Body)
|
||||
|
||||
// Update the server status using the service
|
||||
updatedServer, err := registry.UpdateServerStatus(ctx, serverName, version, statusChange)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error400BadRequest("Failed to update server status", err)
|
||||
}
|
||||
|
||||
return &Response[apiv0.ServerResponse]{
|
||||
Body: *updatedServer,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// buildStatusChangeRequestFromBody constructs a StatusChangeRequest from the request body
|
||||
func buildStatusChangeRequestFromBody(body UpdateServerStatusBody) *service.StatusChangeRequest {
|
||||
var statusMessage *string
|
||||
|
||||
newStatus := model.Status(body.Status)
|
||||
|
||||
// When transitioning to active status, clear status_message
|
||||
if newStatus != model.StatusActive {
|
||||
statusMessage = body.StatusMessage
|
||||
}
|
||||
|
||||
return &service.StatusChangeRequest{
|
||||
NewStatus: newStatus,
|
||||
StatusMessage: statusMessage,
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateAllVersionsStatusInput represents the input for updating all versions' status
|
||||
type UpdateAllVersionsStatusInput struct {
|
||||
Authorization string `header:"Authorization" doc:"Registry JWT token with publish or edit permissions" required:"true"`
|
||||
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
|
||||
Body UpdateServerStatusBody `body:""`
|
||||
}
|
||||
|
||||
// UpdateAllVersionsStatusResponse represents the response for updating all versions' status
|
||||
type UpdateAllVersionsStatusResponse struct {
|
||||
UpdatedCount int `json:"updatedCount" doc:"Number of versions updated"`
|
||||
Servers []apiv0.ServerResponse `json:"servers" doc:"List of all updated server versions"`
|
||||
}
|
||||
|
||||
// RegisterAllVersionsStatusEndpoints registers the all-versions status update endpoint
|
||||
func RegisterAllVersionsStatusEndpoints(api huma.API, pathPrefix string, registry service.RegistryService, cfg *config.Config) {
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
|
||||
// Update all versions status endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "update-server-all-versions-status" + strings.ReplaceAll(pathPrefix, "/", "-"),
|
||||
Method: http.MethodPatch,
|
||||
Path: pathPrefix + "/servers/{serverName}/status",
|
||||
Summary: "Update status for all versions of an MCP server",
|
||||
Description: "Update the status metadata of all versions of an MCP server in a single transaction. Requires publish or edit permission for the server. Either all versions are updated or none on failure.",
|
||||
Tags: []string{"servers"},
|
||||
Security: []map[string][]string{
|
||||
{"bearer": {}},
|
||||
},
|
||||
}, func(ctx context.Context, input *UpdateAllVersionsStatusInput) (*Response[UpdateAllVersionsStatusResponse], error) {
|
||||
// Extract bearer token
|
||||
const bearerPrefix = "Bearer "
|
||||
authHeader := input.Authorization
|
||||
if len(authHeader) < len(bearerPrefix) || !strings.EqualFold(authHeader[:len(bearerPrefix)], bearerPrefix) {
|
||||
return nil, huma.Error401Unauthorized("Invalid Authorization header format. Expected 'Bearer <token>'")
|
||||
}
|
||||
token := authHeader[len(bearerPrefix):]
|
||||
|
||||
// Validate Registry JWT token
|
||||
claims, err := jwtManager.ValidateToken(ctx, token)
|
||||
if err != nil {
|
||||
return nil, huma.Error401Unauthorized("Invalid or expired Registry JWT token", err)
|
||||
}
|
||||
|
||||
// URL-decode the server name
|
||||
serverName, err := url.PathUnescape(input.ServerName)
|
||||
if err != nil {
|
||||
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
|
||||
}
|
||||
|
||||
// Get any version to verify server exists and check permissions
|
||||
// Include deleted servers since we need to be able to restore them
|
||||
currentServer, err := registry.GetServerByName(ctx, serverName, true)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error500InternalServerError("Failed to get server", err)
|
||||
}
|
||||
|
||||
// Verify publish or edit permissions for this server
|
||||
hasPublish := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionPublish, claims.Permissions)
|
||||
hasEdit := jwtManager.HasPermission(currentServer.Server.Name, auth.PermissionActionEdit, claims.Permissions)
|
||||
if !hasPublish && !hasEdit {
|
||||
return nil, huma.Error403Forbidden("You do not have publish or edit permissions for this server")
|
||||
}
|
||||
|
||||
newStatus := model.Status(input.Body.Status)
|
||||
|
||||
// Fetch all versions to validate the bulk status transition
|
||||
allVersions, err := registry.GetAllVersionsByServerName(ctx, serverName, true)
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("Failed to get server versions", err)
|
||||
}
|
||||
|
||||
// Validate bulk status transition - reject if no changes would occur
|
||||
if err := validateBulkStatusTransition(allVersions, newStatus, input.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Build status change request
|
||||
statusChange := buildStatusChangeRequestFromBody(input.Body)
|
||||
|
||||
// Update all versions' status using the service
|
||||
updatedServers, err := registry.UpdateAllVersionsStatus(ctx, serverName, statusChange)
|
||||
if err != nil {
|
||||
if errors.Is(err, database.ErrNotFound) {
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
return nil, huma.Error400BadRequest("Failed to update server status", err)
|
||||
}
|
||||
|
||||
// Convert to response format
|
||||
servers := make([]apiv0.ServerResponse, len(updatedServers))
|
||||
for i, s := range updatedServers {
|
||||
servers[i] = *s
|
||||
}
|
||||
|
||||
return &Response[UpdateAllVersionsStatusResponse]{
|
||||
Body: UpdateAllVersionsStatusResponse{
|
||||
UpdatedCount: len(servers),
|
||||
Servers: servers,
|
||||
},
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// validateBulkStatusTransition validates if a bulk status transition would result in any changes
|
||||
// Returns an error if no changes would occur (all versions already have target status and message)
|
||||
func validateBulkStatusTransition(versions []*apiv0.ServerResponse, newStatus model.Status, body UpdateServerStatusBody) error {
|
||||
if len(versions) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check if any version would have changes applied
|
||||
for _, version := range versions {
|
||||
err := validateStatusTransition(version, newStatus, body)
|
||||
if err == nil {
|
||||
// This version has changes, so the bulk operation is valid
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// No versions would have any changes
|
||||
return huma.Error400BadRequest("No changes to apply: all versions already have the requested status and message")
|
||||
}
|
||||
885
internal/api/handlers/v0/status_test.go
Normal file
885
internal/api/handlers/v0/status_test.go
Normal file
|
|
@ -0,0 +1,885 @@
|
|||
package v0_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
v0 "github.com/modelcontextprotocol/registry/internal/api/handlers/v0"
|
||||
"github.com/modelcontextprotocol/registry/internal/auth"
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
func TestUpdateServerStatusEndpoint(t *testing.T) {
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
|
||||
// Create registry service and test data
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Create test servers for different scenarios
|
||||
testServers := map[string]*apiv0.ServerJSON{
|
||||
"active": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/active-server",
|
||||
Description: "Server in active status",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/active-server",
|
||||
Source: "github",
|
||||
ID: "testuser/active-server",
|
||||
},
|
||||
},
|
||||
"deprecated": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/deprecated-server",
|
||||
Description: "Server in deprecated status",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/deprecated-server",
|
||||
Source: "github",
|
||||
ID: "testuser/deprecated-server",
|
||||
},
|
||||
},
|
||||
"deleted": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/deleted-server",
|
||||
Description: "Server in deleted status",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/deleted-server",
|
||||
Source: "github",
|
||||
ID: "testuser/deleted-server",
|
||||
},
|
||||
},
|
||||
"other": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.otheruser/other-server",
|
||||
Description: "Server owned by another user",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/otheruser/other-server",
|
||||
Source: "github",
|
||||
ID: "otheruser/other-server",
|
||||
},
|
||||
},
|
||||
"multi-version": {
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/multi-version-server",
|
||||
Description: "Server with multiple versions for testing",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/multi-version-server",
|
||||
Source: "github",
|
||||
ID: "testuser/multi-version-server",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Create the test servers
|
||||
for _, server := range testServers {
|
||||
_, err := registryService.CreateServer(context.Background(), server)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
// Set deprecated server to deprecated status
|
||||
_, err = registryService.UpdateServerStatus(context.Background(), testServers["deprecated"].Name, testServers["deprecated"].Version, &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeprecated,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Set deleted server to deleted status
|
||||
_, err = registryService.UpdateServerStatus(context.Background(), testServers["deleted"].Name, testServers["deleted"].Version, &service.StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Add a second version to multi-version server
|
||||
multiVersionV2 := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/multi-version-server",
|
||||
Description: "Server with multiple versions for testing",
|
||||
Version: "2.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/multi-version-server",
|
||||
Source: "github",
|
||||
ID: "testuser/multi-version-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionV2)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
serverName string
|
||||
version string
|
||||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody v0.UpdateServerStatusBody
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
}{
|
||||
{
|
||||
name: "successful status change from active to deprecated",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful status change with message",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deleted",
|
||||
StatusMessage: strPtr("Security vulnerability discovered"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeleted, resp.Meta.Official.Status)
|
||||
assert.NotNil(t, resp.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "Security vulnerability discovered", *resp.Meta.Official.StatusMessage)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful restore from deleted to active",
|
||||
serverName: "io.github.testuser/deleted-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusActive, resp.Meta.Official.Status)
|
||||
// Status message should be cleared when transitioning to active
|
||||
assert.Nil(t, resp.Meta.Official.StatusMessage)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful undeprecate from deprecated to active",
|
||||
serverName: "io.github.testuser/deprecated-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusActive, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "",
|
||||
requestBody: v0.UpdateServerStatusBody{Status: "deprecated"},
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "required header parameter is missing",
|
||||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Invalid Authorization header format",
|
||||
},
|
||||
{
|
||||
name: "invalid token",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authHeader: "Bearer invalid-token",
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Invalid or expired Registry JWT token",
|
||||
},
|
||||
{
|
||||
name: "permission denied - no publish or edit permissions",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: "read", ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have publish or edit permissions for this server",
|
||||
},
|
||||
{
|
||||
name: "successful status change with edit permission only",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful status change with both publish and edit permissions",
|
||||
serverName: "io.github.testuser/active-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusActive, resp.Meta.Official.Status)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "permission denied - wrong namespace",
|
||||
serverName: "io.github.otheruser/other-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have publish or edit permissions for this server",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverName: "io.github.testuser/non-existent",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Server version not found",
|
||||
},
|
||||
{
|
||||
name: "same status transition allowed when updating statusMessage",
|
||||
serverName: "io.github.testuser/deprecated-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
StatusMessage: strPtr("Updated deprecation message"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, model.StatusDeprecated, resp.Meta.Official.Status)
|
||||
assert.NotNil(t, resp.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "Updated deprecation message", *resp.Meta.Official.StatusMessage)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "status_message rejected when setting status to active",
|
||||
serverName: "io.github.testuser/deprecated-server",
|
||||
version: "1.0.0",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
StatusMessage: strPtr("This message should not be allowed"),
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "status_message cannot be provided when setting status to active",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
|
||||
// Register status endpoints
|
||||
v0.RegisterStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Create request body
|
||||
requestBody, err := json.Marshal(tc.requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create request URL with proper encoding
|
||||
encodedServerName := url.PathEscape(tc.serverName)
|
||||
encodedVersion := url.PathEscape(tc.version)
|
||||
requestURL := "/v0/servers/" + encodedServerName + "/versions/" + encodedVersion + "/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, requestURL, bytes.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Set authorization header
|
||||
if tc.authHeader != "" {
|
||||
req.Header.Set("Authorization", tc.authHeader)
|
||||
} else if tc.authClaims != nil {
|
||||
// Generate valid JWT token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), *tc.authClaims)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
}
|
||||
|
||||
// Create response recorder and execute request
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check response
|
||||
if tc.expectedStatus != w.Code {
|
||||
t.Logf("Response body: %s", w.Body.String())
|
||||
}
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
if tc.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tc.expectedError)
|
||||
}
|
||||
|
||||
if tc.expectedStatus == http.StatusOK && tc.checkResult != nil {
|
||||
var response apiv0.ServerResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
tc.checkResult(t, &response)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateServerStatusEndpointSameStatusTransition(t *testing.T) {
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
|
||||
// Create registry service
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Create an active server
|
||||
activeServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/same-status-test",
|
||||
Description: "Server for same status transition test",
|
||||
Version: "1.0.0",
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), activeServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Try to transition from active to active (should fail)
|
||||
requestBody := v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
}
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(activeServer.Name)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/1.0.0/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
assert.Contains(t, w.Body.String(), "No changes to apply: status and message are already set to the provided values")
|
||||
}
|
||||
|
||||
func TestUpdateServerStatusEndpointURLEncoding(t *testing.T) {
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
|
||||
// Create registry service
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Create a server with build metadata version
|
||||
buildMetadataServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/build-metadata-server",
|
||||
Description: "Server with build metadata version",
|
||||
Version: "1.0.0+20130313144700",
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), buildMetadataServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
v0.RegisterStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Update status with URL-encoded version
|
||||
requestBody := v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
StatusMessage: strPtr("Testing URL encoding"),
|
||||
}
|
||||
bodyBytes, err := json.Marshal(requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
encodedName := url.PathEscape(buildMetadataServer.Name)
|
||||
encodedVersion := url.PathEscape(buildMetadataServer.Version)
|
||||
requestURL := "/v0/servers/" + encodedName + "/versions/" + encodedVersion + "/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, requestURL, bytes.NewReader(bodyBytes))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Generate admin token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), auth.JWTClaims{
|
||||
AuthMethod: auth.MethodNone,
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "*"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var response apiv0.ServerResponse
|
||||
err = json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.StatusDeprecated, response.Meta.Official.Status)
|
||||
assert.Equal(t, "1.0.0+20130313144700", response.Server.Version)
|
||||
}
|
||||
|
||||
func TestUpdateAllVersionsStatusEndpoint(t *testing.T) {
|
||||
// Create test config
|
||||
testSeed := make([]byte, ed25519.SeedSize)
|
||||
_, err := rand.Read(testSeed)
|
||||
require.NoError(t, err)
|
||||
cfg := &config.Config{
|
||||
JWTPrivateKey: hex.EncodeToString(testSeed),
|
||||
EnableRegistryValidation: false,
|
||||
}
|
||||
|
||||
// Create registry service and test data
|
||||
registryService := service.NewRegistryService(database.NewTestDB(t), cfg)
|
||||
|
||||
// Create a server with multiple versions
|
||||
multiVersionServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.testuser/multi-version-server",
|
||||
Description: "Server with multiple versions",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/testuser/multi-version-server",
|
||||
Source: "github",
|
||||
ID: "testuser/multi-version-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Add more versions
|
||||
multiVersionServer.Version = "1.1.0"
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
multiVersionServer.Version = "2.0.0"
|
||||
_, err = registryService.CreateServer(context.Background(), multiVersionServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create other user's server
|
||||
otherServer := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "io.github.otheruser/other-server",
|
||||
Description: "Server owned by another user",
|
||||
Version: "1.0.0",
|
||||
Repository: &model.Repository{
|
||||
URL: "https://github.com/otheruser/other-server",
|
||||
Source: "github",
|
||||
ID: "otheruser/other-server",
|
||||
},
|
||||
}
|
||||
_, err = registryService.CreateServer(context.Background(), otherServer)
|
||||
require.NoError(t, err)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
serverName string
|
||||
authClaims *auth.JWTClaims
|
||||
authHeader string
|
||||
requestBody v0.UpdateServerStatusBody
|
||||
expectedStatus int
|
||||
expectedError string
|
||||
checkResult func(*testing.T, *v0.UpdateAllVersionsStatusResponse)
|
||||
}{
|
||||
{
|
||||
name: "successful deprecation of all versions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
StatusMessage: strPtr("This server is deprecated"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
assert.Len(t, resp.Servers, 3)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusDeprecated, server.Meta.Official.Status)
|
||||
assert.NotNil(t, server.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "This server is deprecated", *server.Meta.Official.StatusMessage)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful delete of all versions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deleted",
|
||||
StatusMessage: strPtr("Security issue discovered"),
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusDeleted, server.Meta.Official.Status)
|
||||
assert.NotNil(t, server.Meta.Official.StatusMessage)
|
||||
assert.Equal(t, "Security issue discovered", *server.Meta.Official.StatusMessage)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful reactivation of all versions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusActive, server.Meta.Official.Status)
|
||||
// Status message should be cleared when transitioning to active
|
||||
assert.Nil(t, server.Meta.Official.StatusMessage)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing authorization header",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authHeader: "",
|
||||
requestBody: v0.UpdateServerStatusBody{Status: "deprecated"},
|
||||
expectedStatus: http.StatusUnprocessableEntity,
|
||||
expectedError: "required header parameter is missing",
|
||||
},
|
||||
{
|
||||
name: "invalid authorization header format",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authHeader: "InvalidFormat token123",
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusUnauthorized,
|
||||
expectedError: "Invalid Authorization header format",
|
||||
},
|
||||
{
|
||||
name: "permission denied - no publish or edit permissions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: "read", ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusForbidden,
|
||||
expectedError: "You do not have publish or edit permissions for this server",
|
||||
},
|
||||
{
|
||||
name: "successful status change with edit permission only",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusDeprecated, server.Meta.Official.Status)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "successful status change with both publish and edit permissions",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
{Action: auth.PermissionActionEdit, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusOK,
|
||||
checkResult: func(t *testing.T, resp *v0.UpdateAllVersionsStatusResponse) {
|
||||
t.Helper()
|
||||
assert.Equal(t, 3, resp.UpdatedCount)
|
||||
for _, server := range resp.Servers {
|
||||
assert.Equal(t, model.StatusActive, server.Meta.Official.Status)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bulk no-op when all versions already have target status and message",
|
||||
serverName: "io.github.testuser/multi-version-server",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "active",
|
||||
},
|
||||
expectedStatus: http.StatusBadRequest,
|
||||
expectedError: "No changes to apply: all versions already have the requested status and message",
|
||||
},
|
||||
{
|
||||
name: "server not found",
|
||||
serverName: "io.github.testuser/non-existent",
|
||||
authClaims: &auth.JWTClaims{
|
||||
AuthMethod: auth.MethodGitHubAT,
|
||||
AuthMethodSubject: "testuser",
|
||||
Permissions: []auth.Permission{
|
||||
{Action: auth.PermissionActionPublish, ResourcePattern: "io.github.testuser/*"},
|
||||
},
|
||||
},
|
||||
requestBody: v0.UpdateServerStatusBody{
|
||||
Status: "deprecated",
|
||||
},
|
||||
expectedStatus: http.StatusNotFound,
|
||||
expectedError: "Server not found",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
// Create Huma API
|
||||
mux := http.NewServeMux()
|
||||
api := humago.New(mux, huma.DefaultConfig("Test API", "1.0.0"))
|
||||
|
||||
// Register all-versions status endpoints
|
||||
v0.RegisterAllVersionsStatusEndpoints(api, "/v0", registryService, cfg)
|
||||
|
||||
// Create request body
|
||||
requestBody, err := json.Marshal(tc.requestBody)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create request URL with proper encoding
|
||||
encodedServerName := url.PathEscape(tc.serverName)
|
||||
requestURL := "/v0/servers/" + encodedServerName + "/status"
|
||||
|
||||
req := httptest.NewRequest(http.MethodPatch, requestURL, bytes.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
// Set authorization header
|
||||
if tc.authHeader != "" {
|
||||
req.Header.Set("Authorization", tc.authHeader)
|
||||
} else if tc.authClaims != nil {
|
||||
// Generate valid JWT token
|
||||
jwtManager := auth.NewJWTManager(cfg)
|
||||
tokenResponse, err := jwtManager.GenerateTokenResponse(context.Background(), *tc.authClaims)
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Authorization", "Bearer "+tokenResponse.RegistryToken)
|
||||
}
|
||||
|
||||
// Create response recorder and execute request
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
// Check response
|
||||
if tc.expectedStatus != w.Code {
|
||||
t.Logf("Response body: %s", w.Body.String())
|
||||
}
|
||||
assert.Equal(t, tc.expectedStatus, w.Code)
|
||||
|
||||
if tc.expectedError != "" {
|
||||
assert.Contains(t, w.Body.String(), tc.expectedError)
|
||||
}
|
||||
|
||||
if tc.expectedStatus == http.StatusOK && tc.checkResult != nil {
|
||||
var response v0.UpdateAllVersionsStatusResponse
|
||||
err := json.NewDecoder(w.Body).Decode(&response)
|
||||
require.NoError(t, err)
|
||||
tc.checkResult(t, &response)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// strPtr is a helper function to create a pointer to a string
|
||||
func strPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
|
@ -19,6 +19,8 @@ func RegisterV0Routes(
|
|||
v0.RegisterVersionEndpoint(api, "/v0", versionInfo)
|
||||
v0.RegisterServersEndpoints(api, "/v0", registry)
|
||||
v0.RegisterEditEndpoints(api, "/v0", registry, cfg)
|
||||
v0.RegisterStatusEndpoints(api, "/v0", registry, cfg)
|
||||
v0.RegisterAllVersionsStatusEndpoints(api, "/v0", registry, cfg)
|
||||
v0auth.RegisterAuthEndpoints(api, "/v0", cfg)
|
||||
v0.RegisterPublishEndpoint(api, "/v0", registry, cfg)
|
||||
v0.RegisterValidateEndpoint(api, "/v0")
|
||||
|
|
@ -32,6 +34,8 @@ func RegisterV0_1Routes(
|
|||
v0.RegisterVersionEndpoint(api, "/v0.1", versionInfo)
|
||||
v0.RegisterServersEndpoints(api, "/v0.1", registry)
|
||||
v0.RegisterEditEndpoints(api, "/v0.1", registry, cfg)
|
||||
v0.RegisterStatusEndpoints(api, "/v0.1", registry, cfg)
|
||||
v0.RegisterAllVersionsStatusEndpoints(api, "/v0.1", registry, cfg)
|
||||
v0auth.RegisterAuthEndpoints(api, "/v0.1", cfg)
|
||||
v0.RegisterPublishEndpoint(api, "/v0.1", registry, cfg)
|
||||
v0.RegisterValidateEndpoint(api, "/v0.1")
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
)
|
||||
|
||||
|
|
@ -17,7 +18,7 @@ type PermissionAction string
|
|||
|
||||
const (
|
||||
PermissionActionPublish PermissionAction = "publish"
|
||||
// Intended for admins taking moderation actions only, at least for now
|
||||
// PermissionActionEdit allows editing server configuration.
|
||||
PermissionActionEdit PermissionAction = "edit"
|
||||
)
|
||||
|
||||
|
|
@ -128,7 +129,6 @@ func (j *JWTManager) ValidateToken(_ context.Context, tokenString string) (*JWTC
|
|||
jwt.WithValidMethods([]string{"EdDSA"}),
|
||||
jwt.WithExpirationRequired(),
|
||||
)
|
||||
|
||||
// Validate token
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse token: %w", err)
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
|
||||
"github.com/jackc/pgx/v5"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// Common database errors
|
||||
|
|
@ -21,12 +22,13 @@ var (
|
|||
|
||||
// ServerFilter defines filtering options for server queries
|
||||
type ServerFilter struct {
|
||||
Name *string // for finding versions of same server
|
||||
RemoteURL *string // for duplicate URL detection
|
||||
UpdatedSince *time.Time // for incremental sync filtering
|
||||
SubstringName *string // for substring search on name
|
||||
Version *string // for exact version matching
|
||||
IsLatest *bool // for filtering latest versions only
|
||||
Name *string // for finding versions of same server
|
||||
RemoteURL *string // for duplicate URL detection
|
||||
UpdatedSince *time.Time // for incremental sync filtering
|
||||
SubstringName *string // for substring search on name
|
||||
Version *string // for exact version matching
|
||||
IsLatest *bool // for filtering latest versions only
|
||||
IncludeDeleted *bool // for including deleted packages in results (default: exclude)
|
||||
}
|
||||
|
||||
// Database defines the interface for database operations
|
||||
|
|
@ -36,15 +38,17 @@ type Database interface {
|
|||
// UpdateServer updates an existing server record
|
||||
UpdateServer(ctx context.Context, tx pgx.Tx, serverName, version string, serverJSON *apiv0.ServerJSON) (*apiv0.ServerResponse, error)
|
||||
// SetServerStatus updates the status of a specific server version
|
||||
SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status string) (*apiv0.ServerResponse, error)
|
||||
SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status model.Status, statusMessage *string) (*apiv0.ServerResponse, error)
|
||||
// SetAllVersionsStatus updates the status of all versions of a server in a single query
|
||||
SetAllVersionsStatus(ctx context.Context, tx pgx.Tx, serverName string, status model.Status, statusMessage *string) ([]*apiv0.ServerResponse, error)
|
||||
// ListServers retrieve server entries with optional filtering
|
||||
ListServers(ctx context.Context, tx pgx.Tx, filter *ServerFilter, cursor string, limit int) ([]*apiv0.ServerResponse, string, error)
|
||||
// GetServerByName retrieve a single server by its name
|
||||
GetServerByName(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error)
|
||||
GetServerByName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) (*apiv0.ServerResponse, error)
|
||||
// GetServerByNameAndVersion retrieve specific version of a server by server name and version
|
||||
GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string) (*apiv0.ServerResponse, error)
|
||||
GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string, includeDeleted bool) (*apiv0.ServerResponse, error)
|
||||
// GetAllVersionsByServerName retrieve all versions of a server by server name
|
||||
GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string) ([]*apiv0.ServerResponse, error)
|
||||
GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) ([]*apiv0.ServerResponse, error)
|
||||
// GetCurrentLatestVersion retrieve the current latest version of a server by server name
|
||||
GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error)
|
||||
// CountServerVersions count the number of versions for a server
|
||||
|
|
|
|||
24
internal/database/migrations/013_add_status_fields.sql
Normal file
24
internal/database/migrations/013_add_status_fields.sql
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
-- Add status management fields for deprecation features
|
||||
-- Status values: active, deprecated, deleted
|
||||
|
||||
BEGIN;
|
||||
|
||||
-- Add new columns for status management
|
||||
ALTER TABLE servers ADD COLUMN status_changed_at TIMESTAMP WITH TIME ZONE;
|
||||
ALTER TABLE servers ADD COLUMN status_message TEXT;
|
||||
|
||||
-- Constraint: status_message must not exceed 500 characters
|
||||
ALTER TABLE servers ADD CONSTRAINT check_status_message_length
|
||||
CHECK (length(status_message) <= 500);
|
||||
|
||||
-- Initialize status_changed_at with published_at for existing records
|
||||
UPDATE servers SET status_changed_at = published_at WHERE status_changed_at IS NULL;
|
||||
|
||||
-- Make status_changed_at NOT NULL now that all records have values
|
||||
ALTER TABLE servers ALTER COLUMN status_changed_at SET NOT NULL;
|
||||
|
||||
-- Constraint: status_changed_at must be >= published_at
|
||||
ALTER TABLE servers ADD CONSTRAINT check_status_changed_at_after_published
|
||||
CHECK (status_changed_at >= published_at);
|
||||
|
||||
COMMIT;
|
||||
|
|
@ -79,6 +79,75 @@ func NewPostgreSQL(ctx context.Context, connectionURI string) (*PostgreSQL, erro
|
|||
}, nil
|
||||
}
|
||||
|
||||
// buildFilterConditions constructs WHERE clause conditions from a ServerFilter
|
||||
//
|
||||
//nolint:unparam // argIndex is always 1 currently but kept for API flexibility
|
||||
func buildFilterConditions(filter *ServerFilter, argIndex int) ([]string, []any, int) {
|
||||
var conditions []string
|
||||
var args []any
|
||||
|
||||
if filter == nil {
|
||||
return conditions, args, argIndex
|
||||
}
|
||||
|
||||
if filter.Name != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("server_name = $%d", argIndex))
|
||||
args = append(args, *filter.Name)
|
||||
argIndex++
|
||||
}
|
||||
if filter.RemoteURL != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("EXISTS (SELECT 1 FROM jsonb_array_elements(value->'remotes') AS remote WHERE remote->>'url' = $%d)", argIndex))
|
||||
args = append(args, *filter.RemoteURL)
|
||||
argIndex++
|
||||
}
|
||||
if filter.UpdatedSince != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("updated_at > $%d", argIndex))
|
||||
args = append(args, *filter.UpdatedSince)
|
||||
argIndex++
|
||||
}
|
||||
if filter.SubstringName != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("server_name ILIKE $%d", argIndex))
|
||||
args = append(args, "%"+*filter.SubstringName+"%")
|
||||
argIndex++
|
||||
}
|
||||
if filter.Version != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("version = $%d", argIndex))
|
||||
args = append(args, *filter.Version)
|
||||
argIndex++
|
||||
}
|
||||
if filter.IsLatest != nil {
|
||||
conditions = append(conditions, fmt.Sprintf("is_latest = $%d", argIndex))
|
||||
args = append(args, *filter.IsLatest)
|
||||
argIndex++
|
||||
}
|
||||
if filter.IncludeDeleted == nil || !*filter.IncludeDeleted {
|
||||
conditions = append(conditions, "status != 'deleted'")
|
||||
}
|
||||
|
||||
return conditions, args, argIndex
|
||||
}
|
||||
|
||||
// addCursorCondition adds pagination cursor condition to WHERE clause
|
||||
func addCursorCondition(cursor string, argIndex int) (string, []any, int) {
|
||||
if cursor == "" {
|
||||
return "", nil, argIndex
|
||||
}
|
||||
|
||||
// Parse cursor format: "serverName:version"
|
||||
parts := strings.SplitN(cursor, ":", 2)
|
||||
if len(parts) == 2 {
|
||||
cursorServerName := parts[0]
|
||||
cursorVersion := parts[1]
|
||||
// Use compound condition: (server_name > cursor_name) OR (server_name = cursor_name AND version > cursor_version)
|
||||
condition := fmt.Sprintf("(server_name > $%d OR (server_name = $%d AND version > $%d))", argIndex, argIndex+1, argIndex+2)
|
||||
return condition, []any{cursorServerName, cursorServerName, cursorVersion}, argIndex + 3
|
||||
}
|
||||
|
||||
// Fallback for malformed cursor - treat as server name only for backwards compatibility
|
||||
condition := fmt.Sprintf("server_name > $%d", argIndex)
|
||||
return condition, []any{cursor}, argIndex + 1
|
||||
}
|
||||
|
||||
func (db *PostgreSQL) ListServers(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
|
|
@ -94,64 +163,17 @@ func (db *PostgreSQL) ListServers(
|
|||
return nil, "", ctx.Err()
|
||||
}
|
||||
|
||||
// Build WHERE clause for filtering using dedicated columns
|
||||
var whereConditions []string
|
||||
args := []any{}
|
||||
// Build WHERE clause conditions
|
||||
argIndex := 1
|
||||
whereConditions, args, argIndex := buildFilterConditions(filter, argIndex)
|
||||
|
||||
// Add filters using dedicated columns for better performance
|
||||
if filter != nil {
|
||||
if filter.Name != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("server_name = $%d", argIndex))
|
||||
args = append(args, *filter.Name)
|
||||
argIndex++
|
||||
}
|
||||
if filter.RemoteURL != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("EXISTS (SELECT 1 FROM jsonb_array_elements(value->'remotes') AS remote WHERE remote->>'url' = $%d)", argIndex))
|
||||
args = append(args, *filter.RemoteURL)
|
||||
argIndex++
|
||||
}
|
||||
if filter.UpdatedSince != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("updated_at > $%d", argIndex))
|
||||
args = append(args, *filter.UpdatedSince)
|
||||
argIndex++
|
||||
}
|
||||
if filter.SubstringName != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("server_name ILIKE $%d", argIndex))
|
||||
args = append(args, "%"+*filter.SubstringName+"%")
|
||||
argIndex++
|
||||
}
|
||||
if filter.Version != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("version = $%d", argIndex))
|
||||
args = append(args, *filter.Version)
|
||||
argIndex++
|
||||
}
|
||||
if filter.IsLatest != nil {
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("is_latest = $%d", argIndex))
|
||||
args = append(args, *filter.IsLatest)
|
||||
argIndex++
|
||||
}
|
||||
}
|
||||
|
||||
// Add cursor pagination using compound serverName:version cursor
|
||||
if cursor != "" {
|
||||
// Parse cursor format: "serverName:version"
|
||||
parts := strings.SplitN(cursor, ":", 2)
|
||||
if len(parts) == 2 {
|
||||
cursorServerName := parts[0]
|
||||
cursorVersion := parts[1]
|
||||
|
||||
// Use compound condition: (server_name > cursor_name) OR (server_name = cursor_name AND version > cursor_version)
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("(server_name > $%d OR (server_name = $%d AND version > $%d))", argIndex, argIndex+1, argIndex+2))
|
||||
args = append(args, cursorServerName, cursorServerName, cursorVersion)
|
||||
argIndex += 3
|
||||
} else {
|
||||
// Fallback for malformed cursor - treat as server name only for backwards compatibility
|
||||
whereConditions = append(whereConditions, fmt.Sprintf("server_name > $%d", argIndex))
|
||||
args = append(args, cursor)
|
||||
argIndex++
|
||||
}
|
||||
// Add cursor pagination
|
||||
cursorCondition, cursorArgs, argIndex := addCursorCondition(cursor, argIndex)
|
||||
if cursorCondition != "" {
|
||||
whereConditions = append(whereConditions, cursorCondition)
|
||||
args = append(args, cursorArgs...)
|
||||
}
|
||||
_ = argIndex // Silence unused variable warning
|
||||
|
||||
// Build the WHERE clause
|
||||
whereClause := ""
|
||||
|
|
@ -161,7 +183,7 @@ func (db *PostgreSQL) ListServers(
|
|||
|
||||
// Query servers table with hybrid column/JSON data
|
||||
query := fmt.Sprintf(`
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
%s
|
||||
ORDER BY server_name, version
|
||||
|
|
@ -178,11 +200,12 @@ func (db *PostgreSQL) ListServers(
|
|||
var results []*apiv0.ServerResponse
|
||||
for rows.Next() {
|
||||
var serverName, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var statusChangedAt, publishedAt, updatedAt time.Time
|
||||
var statusMessage *string
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
|
||||
err := rows.Scan(&serverName, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
err := rows.Scan(&serverName, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to scan server row: %w", err)
|
||||
}
|
||||
|
|
@ -198,10 +221,12 @@ func (db *PostgreSQL) ListServers(
|
|||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
Status: model.Status(status),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: statusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -224,25 +249,41 @@ func (db *PostgreSQL) ListServers(
|
|||
}
|
||||
|
||||
// GetServerByName retrieves the latest version of a server by server name
|
||||
func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName string) (*apiv0.ServerResponse, error) {
|
||||
func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
// Build filter conditions
|
||||
isLatest := true
|
||||
filter := &ServerFilter{
|
||||
Name: &serverName,
|
||||
IsLatest: &isLatest,
|
||||
IncludeDeleted: &includeDeleted,
|
||||
}
|
||||
|
||||
argIndex := 1
|
||||
whereConditions, args, _ := buildFilterConditions(filter, argIndex)
|
||||
|
||||
whereClause := ""
|
||||
if len(whereConditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
WHERE server_name = $1 AND is_latest = true
|
||||
%s
|
||||
ORDER BY published_at DESC
|
||||
LIMIT 1
|
||||
`
|
||||
`, whereClause)
|
||||
|
||||
var name, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var isLatest bool
|
||||
var statusChangedAt, publishedAt, updatedAt time.Time
|
||||
var statusMessage *string
|
||||
var valueJSON []byte
|
||||
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, serverName).Scan(&name, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, args...).Scan(&name, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
|
|
@ -261,10 +302,12 @@ func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName
|
|||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
Status: model.Status(status),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: statusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -273,24 +316,40 @@ func (db *PostgreSQL) GetServerByName(ctx context.Context, tx pgx.Tx, serverName
|
|||
}
|
||||
|
||||
// GetServerByNameAndVersion retrieves a specific version of a server by server name and version
|
||||
func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string) (*apiv0.ServerResponse, error) {
|
||||
func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx, serverName string, version string, includeDeleted bool) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
// Build filter conditions
|
||||
filter := &ServerFilter{
|
||||
Name: &serverName,
|
||||
Version: &version,
|
||||
IncludeDeleted: &includeDeleted,
|
||||
}
|
||||
|
||||
argIndex := 1
|
||||
whereConditions, args, _ := buildFilterConditions(filter, argIndex)
|
||||
|
||||
whereClause := ""
|
||||
if len(whereConditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
WHERE server_name = $1 AND version = $2
|
||||
%s
|
||||
LIMIT 1
|
||||
`
|
||||
`, whereClause)
|
||||
|
||||
var name, vers, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var statusChangedAt, publishedAt, updatedAt time.Time
|
||||
var statusMessage *string
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, serverName, version).Scan(&name, &vers, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, args...).Scan(&name, &vers, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
|
|
@ -309,10 +368,12 @@ func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx,
|
|||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
Status: model.Status(status),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: statusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -321,19 +382,33 @@ func (db *PostgreSQL) GetServerByNameAndVersion(ctx context.Context, tx pgx.Tx,
|
|||
}
|
||||
|
||||
// GetAllVersionsByServerName retrieves all versions of a server by server name
|
||||
func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string) ([]*apiv0.ServerResponse, error) {
|
||||
func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx, serverName string, includeDeleted bool) ([]*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT server_name, version, status, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
WHERE server_name = $1
|
||||
ORDER BY published_at DESC
|
||||
`
|
||||
// Build filter conditions
|
||||
filter := &ServerFilter{
|
||||
Name: &serverName,
|
||||
IncludeDeleted: &includeDeleted,
|
||||
}
|
||||
|
||||
rows, err := db.getExecutor(tx).Query(ctx, query, serverName)
|
||||
argIndex := 1
|
||||
whereConditions, args, _ := buildFilterConditions(filter, argIndex)
|
||||
|
||||
whereClause := ""
|
||||
if len(whereConditions) > 0 {
|
||||
whereClause = "WHERE " + strings.Join(whereConditions, " AND ")
|
||||
}
|
||||
|
||||
query := fmt.Sprintf(`
|
||||
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
%s
|
||||
ORDER BY published_at DESC
|
||||
`, whereClause)
|
||||
|
||||
rows, err := db.getExecutor(tx).Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query server versions: %w", err)
|
||||
}
|
||||
|
|
@ -342,11 +417,12 @@ func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx,
|
|||
var results []*apiv0.ServerResponse
|
||||
for rows.Next() {
|
||||
var name, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var statusChangedAt, publishedAt, updatedAt time.Time
|
||||
var statusMessage *string
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
|
||||
err := rows.Scan(&name, &version, &status, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
err := rows.Scan(&name, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &valueJSON)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to scan server row: %w", err)
|
||||
}
|
||||
|
|
@ -362,10 +438,12 @@ func (db *PostgreSQL) GetAllVersionsByServerName(ctx context.Context, tx pgx.Tx,
|
|||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
Status: model.Status(status),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: statusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -407,20 +485,21 @@ func (db *PostgreSQL) CreateServer(ctx context.Context, tx pgx.Tx, serverJSON *a
|
|||
|
||||
// Insert the new server version using composite primary key
|
||||
insertQuery := `
|
||||
INSERT INTO servers (server_name, version, status, published_at, updated_at, is_latest, value)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
INSERT INTO servers (server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
`
|
||||
|
||||
_, err = db.getExecutor(tx).Exec(ctx, insertQuery,
|
||||
serverJSON.Name,
|
||||
serverJSON.Version,
|
||||
string(officialMeta.Status),
|
||||
officialMeta.StatusChangedAt,
|
||||
officialMeta.StatusMessage,
|
||||
officialMeta.PublishedAt,
|
||||
officialMeta.UpdatedAt,
|
||||
officialMeta.IsLatest,
|
||||
valueJSON,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to insert server: %w", err)
|
||||
}
|
||||
|
|
@ -463,14 +542,15 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, serverName, v
|
|||
UPDATE servers
|
||||
SET value = $1, updated_at = NOW()
|
||||
WHERE server_name = $2 AND version = $3
|
||||
RETURNING server_name, version, status, published_at, updated_at, is_latest
|
||||
RETURNING server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest
|
||||
`
|
||||
|
||||
var name, vers, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var statusChangedAt, publishedAt, updatedAt time.Time
|
||||
var statusMessage *string
|
||||
var isLatest bool
|
||||
|
||||
err = db.getExecutor(tx).QueryRow(ctx, query, valueJSON, serverName, version).Scan(&name, &vers, &status, &publishedAt, &updatedAt, &isLatest)
|
||||
err = db.getExecutor(tx).QueryRow(ctx, query, valueJSON, serverName, version).Scan(&name, &vers, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
|
|
@ -483,10 +563,12 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, serverName, v
|
|||
Server: *serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(status),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
Status: model.Status(status),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: statusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -495,25 +577,31 @@ func (db *PostgreSQL) UpdateServer(ctx context.Context, tx pgx.Tx, serverName, v
|
|||
}
|
||||
|
||||
// SetServerStatus updates the status of a specific server version
|
||||
func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status string) (*apiv0.ServerResponse, error) {
|
||||
func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName, version string, status model.Status, statusMessage *string) (*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
// Update the status column
|
||||
// Update the status and related fields
|
||||
// Only update status_changed_at when status actually changes
|
||||
query := `
|
||||
UPDATE servers
|
||||
SET status = $1, updated_at = NOW()
|
||||
SET
|
||||
status = $1,
|
||||
status_changed_at = CASE WHEN status != $1::varchar THEN NOW() ELSE status_changed_at END,
|
||||
updated_at = NOW(),
|
||||
status_message = $4
|
||||
WHERE server_name = $2 AND version = $3
|
||||
RETURNING server_name, version, status, value, published_at, updated_at, is_latest
|
||||
RETURNING server_name, version, status, value, published_at, updated_at, is_latest, status_changed_at, status_message
|
||||
`
|
||||
|
||||
var name, vers, currentStatus string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var publishedAt, updatedAt, statusChangedAt time.Time
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
var resultStatusMessage *string
|
||||
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, status, serverName, version).Scan(&name, &vers, ¤tStatus, &valueJSON, &publishedAt, &updatedAt, &isLatest)
|
||||
err := db.getExecutor(tx).QueryRow(ctx, query, string(status), serverName, version, statusMessage).Scan(&name, &vers, ¤tStatus, &valueJSON, &publishedAt, &updatedAt, &isLatest, &statusChangedAt, &resultStatusMessage)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
|
|
@ -532,10 +620,12 @@ func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName
|
|||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(currentStatus),
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
Status: model.Status(currentStatus),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: resultStatusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
@ -543,6 +633,78 @@ func (db *PostgreSQL) SetServerStatus(ctx context.Context, tx pgx.Tx, serverName
|
|||
return serverResponse, nil
|
||||
}
|
||||
|
||||
// SetAllVersionsStatus updates the status of all versions of a server in a single query
|
||||
func (db *PostgreSQL) SetAllVersionsStatus(ctx context.Context, tx pgx.Tx, serverName string, status model.Status, statusMessage *string) ([]*apiv0.ServerResponse, error) {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
|
||||
// Update the status and related fields for all versions
|
||||
// Only update rows where status or status_message actually changes
|
||||
// Only update status_changed_at when status actually changes
|
||||
query := `
|
||||
UPDATE servers
|
||||
SET
|
||||
status = $1,
|
||||
status_changed_at = CASE WHEN status != $1::varchar THEN NOW() ELSE status_changed_at END,
|
||||
updated_at = NOW(),
|
||||
status_message = $2
|
||||
WHERE server_name = $3
|
||||
AND (status != $1::varchar OR status_message IS DISTINCT FROM $2)
|
||||
RETURNING server_name, version, status, value, published_at, updated_at, is_latest, status_changed_at, status_message
|
||||
`
|
||||
|
||||
rows, err := db.getExecutor(tx).Query(ctx, query, string(status), statusMessage, serverName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to update all server versions status: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var results []*apiv0.ServerResponse
|
||||
for rows.Next() {
|
||||
var name, vers, currentStatus string
|
||||
var publishedAt, updatedAt, statusChangedAt time.Time
|
||||
var isLatest bool
|
||||
var valueJSON []byte
|
||||
var resultStatusMessage *string
|
||||
|
||||
if err := rows.Scan(&name, &vers, ¤tStatus, &valueJSON, &publishedAt, &updatedAt, &isLatest, &statusChangedAt, &resultStatusMessage); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan server row: %w", err)
|
||||
}
|
||||
|
||||
// Unmarshal the JSON data
|
||||
var serverJSON apiv0.ServerJSON
|
||||
if err := json.Unmarshal(valueJSON, &serverJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal server JSON: %w", err)
|
||||
}
|
||||
|
||||
serverResponse := &apiv0.ServerResponse{
|
||||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
Status: model.Status(currentStatus),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: resultStatusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
results = append(results, serverResponse)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("error iterating server rows: %w", err)
|
||||
}
|
||||
|
||||
if len(results) == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// InTransaction executes a function within a database transaction
|
||||
func (db *PostgreSQL) InTransaction(ctx context.Context, fn func(ctx context.Context, tx pgx.Tx) error) error {
|
||||
if ctx.Err() != nil {
|
||||
|
|
@ -615,7 +777,7 @@ func (db *PostgreSQL) GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, se
|
|||
executor := db.getExecutor(tx)
|
||||
|
||||
query := `
|
||||
SELECT server_name, version, status, value, published_at, updated_at, is_latest
|
||||
SELECT server_name, version, status, status_changed_at, status_message, published_at, updated_at, is_latest, value
|
||||
FROM servers
|
||||
WHERE server_name = $1 AND is_latest = true
|
||||
`
|
||||
|
|
@ -623,11 +785,12 @@ func (db *PostgreSQL) GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, se
|
|||
row := executor.QueryRow(ctx, query, serverName)
|
||||
|
||||
var name, version, status string
|
||||
var publishedAt, updatedAt time.Time
|
||||
var statusChangedAt, publishedAt, updatedAt time.Time
|
||||
var statusMessage *string
|
||||
var isLatest bool
|
||||
var jsonValue []byte
|
||||
|
||||
err := row.Scan(&name, &version, &status, &jsonValue, &publishedAt, &updatedAt, &isLatest)
|
||||
err := row.Scan(&name, &version, &status, &statusChangedAt, &statusMessage, &publishedAt, &updatedAt, &isLatest, &jsonValue)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
|
|
@ -646,9 +809,12 @@ func (db *PostgreSQL) GetCurrentLatestVersion(ctx context.Context, tx pgx.Tx, se
|
|||
Server: serverJSON,
|
||||
Meta: apiv0.ResponseMeta{
|
||||
Official: &apiv0.RegistryExtensions{
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
Status: model.Status(status),
|
||||
StatusChangedAt: statusChangedAt,
|
||||
StatusMessage: statusMessage,
|
||||
PublishedAt: publishedAt,
|
||||
UpdatedAt: updatedAt,
|
||||
IsLatest: isLatest,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -7,6 +7,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
"github.com/modelcontextprotocol/registry/internal/validators"
|
||||
|
|
@ -47,8 +48,8 @@ func (s *registryServiceImpl) ListServers(ctx context.Context, filter *database.
|
|||
}
|
||||
|
||||
// GetServerByName retrieves the latest version of a server by its server name
|
||||
func (s *registryServiceImpl) GetServerByName(ctx context.Context, serverName string) (*apiv0.ServerResponse, error) {
|
||||
serverRecord, err := s.db.GetServerByName(ctx, nil, serverName)
|
||||
func (s *registryServiceImpl) GetServerByName(ctx context.Context, serverName string, includeDeleted bool) (*apiv0.ServerResponse, error) {
|
||||
serverRecord, err := s.db.GetServerByName(ctx, nil, serverName, includeDeleted)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -57,8 +58,8 @@ func (s *registryServiceImpl) GetServerByName(ctx context.Context, serverName st
|
|||
}
|
||||
|
||||
// GetServerByNameAndVersion retrieves a specific version of a server by server name and version
|
||||
func (s *registryServiceImpl) GetServerByNameAndVersion(ctx context.Context, serverName string, version string) (*apiv0.ServerResponse, error) {
|
||||
serverRecord, err := s.db.GetServerByNameAndVersion(ctx, nil, serverName, version)
|
||||
func (s *registryServiceImpl) GetServerByNameAndVersion(ctx context.Context, serverName string, version string, includeDeleted bool) (*apiv0.ServerResponse, error) {
|
||||
serverRecord, err := s.db.GetServerByNameAndVersion(ctx, nil, serverName, version, includeDeleted)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -67,8 +68,8 @@ func (s *registryServiceImpl) GetServerByNameAndVersion(ctx context.Context, ser
|
|||
}
|
||||
|
||||
// GetAllVersionsByServerName retrieves all versions of a server by server name
|
||||
func (s *registryServiceImpl) GetAllVersionsByServerName(ctx context.Context, serverName string) ([]*apiv0.ServerResponse, error) {
|
||||
serverRecords, err := s.db.GetAllVersionsByServerName(ctx, nil, serverName)
|
||||
func (s *registryServiceImpl) GetAllVersionsByServerName(ctx context.Context, serverName string, includeDeleted bool) ([]*apiv0.ServerResponse, error) {
|
||||
serverRecords, err := s.db.GetAllVersionsByServerName(ctx, nil, serverName, includeDeleted)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -152,10 +153,11 @@ func (s *registryServiceImpl) createServerInTransaction(ctx context.Context, tx
|
|||
|
||||
// Create metadata for the new server
|
||||
officialMeta := &apiv0.RegistryExtensions{
|
||||
Status: model.StatusActive, /* New versions are active by default */
|
||||
PublishedAt: publishTime,
|
||||
UpdatedAt: publishTime,
|
||||
IsLatest: isNewLatest,
|
||||
Status: model.StatusActive, /* New versions are active by default */
|
||||
StatusChangedAt: publishTime,
|
||||
PublishedAt: publishTime,
|
||||
UpdatedAt: publishTime,
|
||||
IsLatest: isNewLatest,
|
||||
}
|
||||
|
||||
// Insert new server version
|
||||
|
|
@ -186,17 +188,18 @@ func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context,
|
|||
}
|
||||
|
||||
// UpdateServer updates an existing server with new details
|
||||
func (s *registryServiceImpl) UpdateServer(ctx context.Context, serverName, version string, req *apiv0.ServerJSON, newStatus *string) (*apiv0.ServerResponse, error) {
|
||||
func (s *registryServiceImpl) UpdateServer(ctx context.Context, serverName, version string, req *apiv0.ServerJSON, statusChange *StatusChangeRequest) (*apiv0.ServerResponse, error) {
|
||||
// Wrap the entire operation in a transaction
|
||||
return database.InTransactionT(ctx, s.db, func(ctx context.Context, tx pgx.Tx) (*apiv0.ServerResponse, error) {
|
||||
return s.updateServerInTransaction(ctx, tx, serverName, version, req, newStatus)
|
||||
return s.updateServerInTransaction(ctx, tx, serverName, version, req, statusChange)
|
||||
})
|
||||
}
|
||||
|
||||
// updateServerInTransaction contains the actual UpdateServer logic within a transaction
|
||||
func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx pgx.Tx, serverName, version string, req *apiv0.ServerJSON, newStatus *string) (*apiv0.ServerResponse, error) {
|
||||
func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx pgx.Tx, serverName, version string, req *apiv0.ServerJSON, statusChange *StatusChangeRequest) (*apiv0.ServerResponse, error) {
|
||||
// Get current server to check if it's deleted or being deleted
|
||||
currentServer, err := s.db.GetServerByNameAndVersion(ctx, tx, serverName, version)
|
||||
// Include deleted servers since we may need to update or restore them
|
||||
currentServer, err := s.db.GetServerByNameAndVersion(ctx, tx, serverName, version, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -205,7 +208,7 @@ func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx
|
|||
// 1. Server is currently deleted, OR
|
||||
// 2. Server is being set to deleted status
|
||||
currentlyDeleted := currentServer.Meta.Official != nil && currentServer.Meta.Official.Status == model.StatusDeleted
|
||||
beingDeleted := newStatus != nil && *newStatus == string(model.StatusDeleted)
|
||||
beingDeleted := statusChange != nil && statusChange.NewStatus == model.StatusDeleted
|
||||
skipRegistryValidation := currentlyDeleted || beingDeleted
|
||||
|
||||
// Validate the request, potentially skipping registry validation for deleted servers
|
||||
|
|
@ -233,8 +236,8 @@ func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx
|
|||
}
|
||||
|
||||
// Handle status change if provided
|
||||
if newStatus != nil {
|
||||
updatedWithStatus, err := s.db.SetServerStatus(ctx, tx, serverName, version, *newStatus)
|
||||
if statusChange != nil {
|
||||
updatedWithStatus, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -243,3 +246,78 @@ func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx
|
|||
|
||||
return updatedServerResponse, nil
|
||||
}
|
||||
|
||||
// UpdateServerStatus updates only the status metadata of a server version
|
||||
func (s *registryServiceImpl) UpdateServerStatus(ctx context.Context, serverName, version string, statusChange *StatusChangeRequest) (*apiv0.ServerResponse, error) {
|
||||
// Wrap the entire operation in a transaction
|
||||
return database.InTransactionT(ctx, s.db, func(ctx context.Context, tx pgx.Tx) (*apiv0.ServerResponse, error) {
|
||||
return s.updateServerStatusInTransaction(ctx, tx, serverName, version, statusChange)
|
||||
})
|
||||
}
|
||||
|
||||
// updateServerStatusInTransaction contains the actual UpdateServerStatus logic within a transaction
|
||||
func (s *registryServiceImpl) updateServerStatusInTransaction(ctx context.Context, tx pgx.Tx, serverName, version string, statusChange *StatusChangeRequest) (*apiv0.ServerResponse, error) {
|
||||
// Get current server to verify it exists and check current status
|
||||
// Include deleted servers since we may need to restore them
|
||||
currentServer, err := s.db.GetServerByNameAndVersion(ctx, tx, serverName, version, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Acquire advisory lock to prevent concurrent edits of servers with same name
|
||||
if err := s.db.AcquirePublishLock(ctx, tx, serverName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// When transitioning to active from deleted, validate remote URLs don't conflict
|
||||
if statusChange.NewStatus == model.StatusActive &&
|
||||
currentServer.Meta.Official != nil &&
|
||||
currentServer.Meta.Official.Status == model.StatusDeleted {
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, tx, currentServer.Server); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Update only the status metadata
|
||||
return s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage)
|
||||
}
|
||||
|
||||
// UpdateAllVersionsStatus updates the status metadata of all versions of a server in a single transaction
|
||||
func (s *registryServiceImpl) UpdateAllVersionsStatus(ctx context.Context, serverName string, statusChange *StatusChangeRequest) ([]*apiv0.ServerResponse, error) {
|
||||
// Wrap the entire operation in a transaction
|
||||
return database.InTransactionT(ctx, s.db, func(ctx context.Context, tx pgx.Tx) ([]*apiv0.ServerResponse, error) {
|
||||
return s.updateAllVersionsStatusInTransaction(ctx, tx, serverName, statusChange)
|
||||
})
|
||||
}
|
||||
|
||||
// updateAllVersionsStatusInTransaction contains the actual UpdateAllVersionsStatus logic within a transaction
|
||||
func (s *registryServiceImpl) updateAllVersionsStatusInTransaction(ctx context.Context, tx pgx.Tx, serverName string, statusChange *StatusChangeRequest) ([]*apiv0.ServerResponse, error) {
|
||||
// Acquire advisory lock to prevent concurrent edits of servers with same name
|
||||
if err := s.db.AcquirePublishLock(ctx, tx, serverName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// When transitioning to active, validate remote URLs for any versions currently deleted
|
||||
if statusChange.NewStatus == model.StatusActive {
|
||||
includeDeleted := true
|
||||
|
||||
// When transitioning to active, it means the current status is either deprecated or deleted, so it should include deleted server also
|
||||
filter := &database.ServerFilter{Name: &serverName, IncludeDeleted: &includeDeleted}
|
||||
versions, _, err := s.db.ListServers(ctx, tx, filter, "", 1000)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list server versions: %w", err)
|
||||
}
|
||||
|
||||
for _, version := range versions {
|
||||
if version.Meta.Official != nil &&
|
||||
version.Meta.Official.Status == model.StatusDeleted {
|
||||
if err := s.validateNoDuplicateRemoteURLs(ctx, tx, version.Server); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update all versions' status in a single database call
|
||||
return s.db.SetAllVersionsStatus(ctx, tx, serverName, statusChange.NewStatus, statusChange.StatusMessage)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,12 +8,13 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/internal/config"
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
|
||||
|
|
@ -177,7 +178,7 @@ func TestGetServerByName(t *testing.T) {
|
|||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.GetServerByName(ctx, tt.serverName)
|
||||
result, err := service.GetServerByName(ctx, tt.serverName, false)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
|
|
@ -270,7 +271,7 @@ func TestGetServerByNameAndVersion(t *testing.T) {
|
|||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.GetServerByNameAndVersion(ctx, tt.serverName, tt.version)
|
||||
result, err := service.GetServerByNameAndVersion(ctx, tt.serverName, tt.version, false)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
|
|
@ -366,7 +367,7 @@ func TestGetAllVersionsByServerName(t *testing.T) {
|
|||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.GetAllVersionsByServerName(ctx, tt.serverName)
|
||||
result, err := service.GetAllVersionsByServerName(ctx, tt.serverName, false)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
|
|
@ -425,7 +426,7 @@ func TestCreateServerConcurrentVersionsNoRace(t *testing.T) {
|
|||
}
|
||||
|
||||
// Query database to check the final state after all creates complete
|
||||
allVersions, err := service.GetAllVersionsByServerName(ctx, serverName)
|
||||
allVersions, err := service.GetAllVersionsByServerName(ctx, serverName, false)
|
||||
require.NoError(t, err, "failed to get all versions")
|
||||
|
||||
latestCount := 0
|
||||
|
|
@ -466,7 +467,7 @@ func TestUpdateServer(t *testing.T) {
|
|||
serverName string
|
||||
version string
|
||||
updatedServer *apiv0.ServerJSON
|
||||
newStatus *string
|
||||
statusChange *StatusChangeRequest
|
||||
expectError bool
|
||||
errorMsg string
|
||||
checkResult func(*testing.T, *apiv0.ServerResponse)
|
||||
|
|
@ -503,7 +504,9 @@ func TestUpdateServer(t *testing.T) {
|
|||
Description: "Updated with status change",
|
||||
Version: version,
|
||||
},
|
||||
newStatus: stringPtr(string(model.StatusDeprecated)),
|
||||
statusChange: &StatusChangeRequest{
|
||||
NewStatus: model.StatusDeprecated,
|
||||
},
|
||||
expectError: false,
|
||||
checkResult: func(t *testing.T, result *apiv0.ServerResponse) {
|
||||
t.Helper()
|
||||
|
|
@ -528,7 +531,7 @@ func TestUpdateServer(t *testing.T) {
|
|||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := service.UpdateServer(ctx, tt.serverName, tt.version, tt.updatedServer, tt.newStatus)
|
||||
result, err := service.UpdateServer(ctx, tt.serverName, tt.version, tt.updatedServer, tt.statusChange)
|
||||
|
||||
if tt.expectError {
|
||||
assert.Error(t, err)
|
||||
|
|
@ -580,12 +583,14 @@ func TestUpdateServer_SkipValidationForDeletedServers(t *testing.T) {
|
|||
service.(*registryServiceImpl).cfg.EnableRegistryValidation = originalConfig
|
||||
|
||||
// First, set server to deleted status
|
||||
deletedStatus := string(model.StatusDeleted)
|
||||
_, err = service.UpdateServer(ctx, serverName, version, invalidServer, &deletedStatus)
|
||||
deletedStatusChange := &StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
}
|
||||
_, err = service.UpdateServer(ctx, serverName, version, invalidServer, deletedStatusChange)
|
||||
require.NoError(t, err, "should be able to set server to deleted (validation should be skipped)")
|
||||
|
||||
// Verify server is now deleted
|
||||
updatedServer, err := service.GetServerByNameAndVersion(ctx, serverName, version)
|
||||
// Verify server is now deleted (need includeDeleted=true to find it)
|
||||
updatedServer, err := service.GetServerByNameAndVersion(ctx, serverName, version, true)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, model.StatusDeleted, updatedServer.Meta.Official.Status)
|
||||
|
||||
|
|
@ -635,8 +640,10 @@ func TestUpdateServer_SkipValidationForDeletedServers(t *testing.T) {
|
|||
service.(*registryServiceImpl).cfg.EnableRegistryValidation = originalConfig
|
||||
|
||||
// Update server and set to deleted in same operation - should skip validation
|
||||
newDeletedStatus := string(model.StatusDeleted)
|
||||
result2, err := service.UpdateServer(ctx, "com.example/being-deleted-test", "1.0.0", activeServer, &newDeletedStatus)
|
||||
newDeletedStatusChange := &StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
}
|
||||
result2, err := service.UpdateServer(ctx, "com.example/being-deleted-test", "1.0.0", activeServer, newDeletedStatusChange)
|
||||
assert.NoError(t, err, "updating server being set to deleted should skip registry validation")
|
||||
assert.NotNil(t, result2)
|
||||
assert.Equal(t, model.StatusDeleted, result2.Meta.Official.Status)
|
||||
|
|
@ -767,14 +774,14 @@ func TestVersionComparison(t *testing.T) {
|
|||
}
|
||||
|
||||
// Get the latest version - should be 2.1.0 based on semantic versioning
|
||||
latest, err := service.GetServerByName(ctx, serverName)
|
||||
latest, err := service.GetServerByName(ctx, serverName, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "2.1.0", latest.Server.Version, "Latest version should be 2.1.0")
|
||||
assert.True(t, latest.Meta.Official.IsLatest)
|
||||
|
||||
// Verify only one version is marked as latest
|
||||
allVersions, err := service.GetAllVersionsByServerName(ctx, serverName)
|
||||
allVersions, err := service.GetAllVersionsByServerName(ctx, serverName, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
latestCount := 0
|
||||
|
|
@ -786,6 +793,195 @@ func TestVersionComparison(t *testing.T) {
|
|||
assert.Equal(t, 1, latestCount, "Exactly one version should be marked as latest")
|
||||
}
|
||||
|
||||
func TestUpdateServerStatus_ValidateRemoteURLsOnRestoreToActive(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
remoteURL := "https://api.example.com/mcp"
|
||||
|
||||
// Create Server A with a remote URL
|
||||
serverA := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/server-a",
|
||||
Description: "Server A with remote URL",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: remoteURL},
|
||||
},
|
||||
}
|
||||
_, err := service.CreateServer(ctx, serverA)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete Server A
|
||||
_, err = service.UpdateServerStatus(ctx, "com.example/server-a", "1.0.0", &StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Server B with the same remote URL (should succeed since A is deleted)
|
||||
serverB := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/server-b",
|
||||
Description: "Server B with same remote URL",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: remoteURL},
|
||||
},
|
||||
}
|
||||
_, err = service.CreateServer(ctx, serverB)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Try to restore Server A to active - should fail due to URL conflict
|
||||
_, err = service.UpdateServerStatus(ctx, "com.example/server-a", "1.0.0", &StatusChangeRequest{
|
||||
NewStatus: model.StatusActive,
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "remote URL")
|
||||
assert.Contains(t, err.Error(), "already used by server")
|
||||
}
|
||||
|
||||
func TestUpdateServerStatus_ValidateRemoteURLsOnRestoreFromDeleted(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
remoteURL := "https://api.deleted.com/mcp"
|
||||
|
||||
// Create Server A with a remote URL and delete it
|
||||
serverA := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/deleted-server",
|
||||
Description: "Server to be deleted",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: remoteURL},
|
||||
},
|
||||
}
|
||||
_, err := service.CreateServer(ctx, serverA)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete Server A
|
||||
_, err = service.UpdateServerStatus(ctx, "com.example/deleted-server", "1.0.0", &StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Server B with the same remote URL (should succeed since A is deleted)
|
||||
serverB := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/new-server",
|
||||
Description: "New server with same remote URL",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: remoteURL},
|
||||
},
|
||||
}
|
||||
_, err = service.CreateServer(ctx, serverB)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Try to restore deleted server to active - should fail due to URL conflict
|
||||
_, err = service.UpdateServerStatus(ctx, "com.example/deleted-server", "1.0.0", &StatusChangeRequest{
|
||||
NewStatus: model.StatusActive,
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "remote URL")
|
||||
assert.Contains(t, err.Error(), "already used by server")
|
||||
}
|
||||
|
||||
func TestUpdateAllVersionsStatus_ValidateRemoteURLsOnRestoreToActive(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
remoteURL := "https://api.allversions.com/mcp"
|
||||
|
||||
// Create Server A with multiple versions
|
||||
serverAv1 := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/multi-version-server",
|
||||
Description: "Server A version 1",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: remoteURL},
|
||||
},
|
||||
}
|
||||
_, err := service.CreateServer(ctx, serverAv1)
|
||||
require.NoError(t, err)
|
||||
|
||||
serverAv2 := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/multi-version-server",
|
||||
Description: "Server A version 2",
|
||||
Version: "2.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: remoteURL},
|
||||
},
|
||||
}
|
||||
_, err = service.CreateServer(ctx, serverAv2)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete all versions of Server A
|
||||
_, err = service.UpdateAllVersionsStatus(ctx, "com.example/multi-version-server", &StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Create Server B with the same remote URL
|
||||
serverB := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/conflicting-server",
|
||||
Description: "Server B with same remote URL",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: remoteURL},
|
||||
},
|
||||
}
|
||||
_, err = service.CreateServer(ctx, serverB)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Try to restore all versions of Server A to active - should fail
|
||||
_, err = service.UpdateAllVersionsStatus(ctx, "com.example/multi-version-server", &StatusChangeRequest{
|
||||
NewStatus: model.StatusActive,
|
||||
})
|
||||
assert.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "remote URL")
|
||||
assert.Contains(t, err.Error(), "already used by server")
|
||||
}
|
||||
|
||||
func TestUpdateServerStatus_NoConflictWhenRestoringWithUniqueURLs(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
testDB := database.NewTestDB(t)
|
||||
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
|
||||
|
||||
// Create and delete a server
|
||||
server := &apiv0.ServerJSON{
|
||||
Schema: model.CurrentSchemaURL,
|
||||
Name: "com.example/unique-url-server",
|
||||
Description: "Server with unique URL",
|
||||
Version: "1.0.0",
|
||||
Remotes: []model.Transport{
|
||||
{Type: "streamable-http", URL: "https://unique.example.com/mcp"},
|
||||
},
|
||||
}
|
||||
_, err := service.CreateServer(ctx, server)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Delete the server
|
||||
_, err = service.UpdateServerStatus(ctx, "com.example/unique-url-server", "1.0.0", &StatusChangeRequest{
|
||||
NewStatus: model.StatusDeleted,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Restore to active - should succeed since URL is still unique
|
||||
result, err := service.UpdateServerStatus(ctx, "com.example/unique-url-server", "1.0.0", &StatusChangeRequest{
|
||||
NewStatus: model.StatusActive,
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, result)
|
||||
assert.Equal(t, model.StatusActive, result.Meta.Official.Status)
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
func stringPtr(s string) *string {
|
||||
return &s
|
||||
|
|
|
|||
|
|
@ -5,20 +5,31 @@ import (
|
|||
|
||||
"github.com/modelcontextprotocol/registry/internal/database"
|
||||
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
|
||||
"github.com/modelcontextprotocol/registry/pkg/model"
|
||||
)
|
||||
|
||||
// StatusChangeRequest represents a request to change a server's status
|
||||
type StatusChangeRequest struct {
|
||||
NewStatus model.Status `json:"newStatus"`
|
||||
StatusMessage *string `json:"statusMessage,omitempty"`
|
||||
}
|
||||
|
||||
// RegistryService defines the interface for registry operations
|
||||
type RegistryService interface {
|
||||
// ListServers retrieve all servers with optional filtering
|
||||
ListServers(ctx context.Context, filter *database.ServerFilter, cursor string, limit int) ([]*apiv0.ServerResponse, string, error)
|
||||
// GetServerByName retrieve latest version of a server by server name
|
||||
GetServerByName(ctx context.Context, serverName string) (*apiv0.ServerResponse, error)
|
||||
GetServerByName(ctx context.Context, serverName string, includeDeleted bool) (*apiv0.ServerResponse, error)
|
||||
// GetServerByNameAndVersion retrieve specific version of a server by server name and version
|
||||
GetServerByNameAndVersion(ctx context.Context, serverName string, version string) (*apiv0.ServerResponse, error)
|
||||
GetServerByNameAndVersion(ctx context.Context, serverName string, version string, includeDeleted bool) (*apiv0.ServerResponse, error)
|
||||
// GetAllVersionsByServerName retrieve all versions of a server by server name
|
||||
GetAllVersionsByServerName(ctx context.Context, serverName string) ([]*apiv0.ServerResponse, error)
|
||||
GetAllVersionsByServerName(ctx context.Context, serverName string, includeDeleted bool) ([]*apiv0.ServerResponse, error)
|
||||
// CreateServer creates a new server version
|
||||
CreateServer(ctx context.Context, req *apiv0.ServerJSON) (*apiv0.ServerResponse, error)
|
||||
// UpdateServer updates an existing server and optionally its status
|
||||
UpdateServer(ctx context.Context, serverName, version string, req *apiv0.ServerJSON, newStatus *string) (*apiv0.ServerResponse, error)
|
||||
UpdateServer(ctx context.Context, serverName, version string, req *apiv0.ServerJSON, statusChange *StatusChangeRequest) (*apiv0.ServerResponse, error)
|
||||
// UpdateServerStatus updates only the status metadata of a server version
|
||||
UpdateServerStatus(ctx context.Context, serverName, version string, statusChange *StatusChangeRequest) (*apiv0.ServerResponse, error)
|
||||
// UpdateAllVersionsStatus updates the status metadata of all versions of a server in a single transaction
|
||||
UpdateAllVersionsStatus(ctx context.Context, serverName string, statusChange *StatusChangeRequest) ([]*apiv0.ServerResponse, error)
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue