registry/internal/service/registry_service.go
Preeti Dewani bb84ea69e8
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
2026-02-27 09:00:07 -08:00

323 lines
12 KiB
Go

package service
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/modelcontextprotocol/registry/internal/config"
"github.com/modelcontextprotocol/registry/internal/database"
"github.com/modelcontextprotocol/registry/internal/validators"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/modelcontextprotocol/registry/pkg/model"
)
const maxServerVersionsPerServer = 10000
// registryServiceImpl implements the RegistryService interface using our Database
type registryServiceImpl struct {
db database.Database
cfg *config.Config
}
// NewRegistryService creates a new registry service with the provided database
func NewRegistryService(db database.Database, cfg *config.Config) RegistryService {
return &registryServiceImpl{
db: db,
cfg: cfg,
}
}
// ListServers returns registry entries with cursor-based pagination and optional filtering
func (s *registryServiceImpl) ListServers(ctx context.Context, filter *database.ServerFilter, cursor string, limit int) ([]*apiv0.ServerResponse, string, error) {
// If limit is not set or negative, use a default limit
if limit <= 0 {
limit = 30
}
// Use the database's ListServers method with pagination and filtering
serverRecords, nextCursor, err := s.db.ListServers(ctx, nil, filter, cursor, limit)
if err != nil {
return nil, "", err
}
return serverRecords, nextCursor, nil
}
// GetServerByName retrieves the latest version of a server by its server name
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
}
return serverRecord, nil
}
// GetServerByNameAndVersion retrieves a specific version of a server by server name and 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
}
return serverRecord, nil
}
// GetAllVersionsByServerName retrieves all versions of a server by server name
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
}
return serverRecords, nil
}
// CreateServer creates a new server version
func (s *registryServiceImpl) CreateServer(ctx context.Context, req *apiv0.ServerJSON) (*apiv0.ServerResponse, error) {
// Wrap the entire operation in a transaction
return database.InTransactionT(ctx, s.db, func(ctx context.Context, tx pgx.Tx) (*apiv0.ServerResponse, error) {
return s.createServerInTransaction(ctx, tx, req)
})
}
// createServerInTransaction contains the actual CreateServer logic within a transaction
func (s *registryServiceImpl) createServerInTransaction(ctx context.Context, tx pgx.Tx, req *apiv0.ServerJSON) (*apiv0.ServerResponse, error) {
// Validate the request
if err := validators.ValidatePublishRequest(ctx, *req, s.cfg); err != nil {
return nil, err
}
publishTime := time.Now()
serverJSON := *req
// Acquire advisory lock to prevent concurrent publishes of the same server
if err := s.db.AcquirePublishLock(ctx, tx, serverJSON.Name); err != nil {
return nil, err
}
// Check for duplicate remote URLs
if err := s.validateNoDuplicateRemoteURLs(ctx, tx, serverJSON); err != nil {
return nil, err
}
// Check we haven't exceeded the maximum versions allowed for a server
versionCount, err := s.db.CountServerVersions(ctx, tx, serverJSON.Name)
if err != nil && !errors.Is(err, database.ErrNotFound) {
return nil, err
}
if versionCount >= maxServerVersionsPerServer {
return nil, database.ErrMaxServersReached
}
// Check this isn't a duplicate version
versionExists, err := s.db.CheckVersionExists(ctx, tx, serverJSON.Name, serverJSON.Version)
if err != nil {
return nil, err
}
if versionExists {
return nil, database.ErrInvalidVersion
}
// Get current latest version to determine if new version should be latest
currentLatest, err := s.db.GetCurrentLatestVersion(ctx, tx, serverJSON.Name)
if err != nil && !errors.Is(err, database.ErrNotFound) {
return nil, err
}
// Determine if this version should be marked as latest
isNewLatest := true
if currentLatest != nil {
var existingPublishedAt time.Time
if currentLatest.Meta.Official != nil {
existingPublishedAt = currentLatest.Meta.Official.PublishedAt
}
isNewLatest = CompareVersions(
serverJSON.Version,
currentLatest.Server.Version,
publishTime,
existingPublishedAt,
) > 0
}
// Unmark old latest version if needed
if isNewLatest && currentLatest != nil {
if err := s.db.UnmarkAsLatest(ctx, tx, serverJSON.Name); err != nil {
return nil, err
}
}
// Create metadata for the new server
officialMeta := &apiv0.RegistryExtensions{
Status: model.StatusActive, /* New versions are active by default */
StatusChangedAt: publishTime,
PublishedAt: publishTime,
UpdatedAt: publishTime,
IsLatest: isNewLatest,
}
// Insert new server version
return s.db.CreateServer(ctx, tx, &serverJSON, officialMeta)
}
// validateNoDuplicateRemoteURLs checks that no other server is using the same remote URLs
func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context, tx pgx.Tx, serverDetail apiv0.ServerJSON) error {
// Check each remote URL in the new server for conflicts
for _, remote := range serverDetail.Remotes {
// Use filter to find servers with this remote URL
filter := &database.ServerFilter{RemoteURL: &remote.URL}
conflictingServers, _, err := s.db.ListServers(ctx, tx, filter, "", 1000)
if err != nil {
return fmt.Errorf("failed to check remote URL conflict: %w", err)
}
// Check if any conflicting server has a different name
for _, conflictingServer := range conflictingServers {
if conflictingServer.Server.Name != serverDetail.Name {
return fmt.Errorf("remote URL %s is already used by server %s", remote.URL, conflictingServer.Server.Name)
}
}
}
return nil
}
// UpdateServer updates an existing server with new details
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, 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, statusChange *StatusChangeRequest) (*apiv0.ServerResponse, error) {
// Get current server to check if it's deleted or being deleted
// 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
}
// Skip registry validation if:
// 1. Server is currently deleted, OR
// 2. Server is being set to deleted status
currentlyDeleted := currentServer.Meta.Official != nil && currentServer.Meta.Official.Status == model.StatusDeleted
beingDeleted := statusChange != nil && statusChange.NewStatus == model.StatusDeleted
skipRegistryValidation := currentlyDeleted || beingDeleted
// Validate the request, potentially skipping registry validation for deleted servers
if err := validators.ValidateUpdateRequest(ctx, *req, s.cfg, skipRegistryValidation); err != nil {
return nil, err
}
// Acquire advisory lock to prevent concurrent edits of servers with same name
if err := s.db.AcquirePublishLock(ctx, tx, serverName); err != nil {
return nil, err
}
// Merge the request with the current server, preserving metadata
updatedServer := *req
// Check for duplicate remote URLs using the updated server
if err := s.validateNoDuplicateRemoteURLs(ctx, tx, updatedServer); err != nil {
return nil, err
}
// Update server in database
updatedServerResponse, err := s.db.UpdateServer(ctx, tx, serverName, version, &updatedServer)
if err != nil {
return nil, err
}
// Handle status change if provided
if statusChange != nil {
updatedWithStatus, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage)
if err != nil {
return nil, err
}
return updatedWithStatus, nil
}
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)
}