registry/internal/api/handlers/v0/servers.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

234 lines
9 KiB
Go

package v0
import (
"context"
"errors"
"net/http"
"net/url"
"reflect"
"strings"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/modelcontextprotocol/registry/internal/database"
"github.com/modelcontextprotocol/registry/internal/service"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
)
const errRecordNotFound = "record not found"
// 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"`
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
type ServerDetailInput struct {
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
}
// ServerVersionDetailInput represents the input for getting a specific version
type ServerVersionDetailInput struct {
ServerName string `path:"serverName" doc:"URL-encoded server name" example:"com.example%2Fmy-server"`
Version string `path:"version" doc:"URL-encoded server version" example:"1.0.0"`
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"`
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
func RegisterServersEndpoints(api huma.API, pathPrefix string, registry service.RegistryService) {
// List servers endpoint
huma.Register(api, huma.Operation{
OperationID: "list-servers" + strings.ReplaceAll(pathPrefix, "/", "-"),
Method: http.MethodGet,
Path: pathPrefix + "/servers",
Summary: "List MCP servers",
Description: "Get a paginated list of MCP servers from the registry",
Tags: []string{"servers"},
}, func(ctx context.Context, input *ListServersInput) (*Response[apiv0.ServerListResponse], error) {
// Build filter from input parameters
filter := &database.ServerFilter{}
// Parse updated_since parameter
if input.UpdatedSince != "" {
// Parse RFC3339 format
if updatedTime, err := time.Parse(time.RFC3339, input.UpdatedSince); err == nil {
filter.UpdatedSince = &updatedTime
} else {
return nil, huma.Error400BadRequest("Invalid updated_since format: expected RFC3339 timestamp (e.g., 2025-08-07T13:15:04.280Z)")
}
}
// Handle search parameter
if input.Search != "" {
filter.SubstringName = &input.Search
}
// Handle version parameter
if input.Version != "" {
if input.Version == "latest" {
// Special case: filter for latest versions
isLatest := true
filter.IsLatest = &isLatest
} else {
// Future: exact version matching
filter.Version = &input.Version
}
}
// 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 {
return nil, huma.Error500InternalServerError("Failed to get registry list", err)
}
// Convert []*ServerResponse to []ServerResponse
serverValues := make([]apiv0.ServerResponse, len(servers))
for i, server := range servers {
serverValues[i] = *server
}
return &Response[apiv0.ServerListResponse]{
Body: apiv0.ServerListResponse{
Servers: serverValues,
Metadata: apiv0.Metadata{
NextCursor: nextCursor,
Count: len(servers),
},
},
}, nil
})
// Get specific server version endpoint (supports "latest" as special version)
huma.Register(api, huma.Operation{
OperationID: "get-server-version" + strings.ReplaceAll(pathPrefix, "/", "-"),
Method: http.MethodGet,
Path: pathPrefix + "/servers/{serverName}/versions/{version}",
Summary: "Get specific MCP server version",
Description: "Get detailed information about a specific version of an MCP server. Use the special version 'latest' to get the latest version.",
Tags: []string{"servers"},
}, func(ctx context.Context, input *ServerVersionDetailInput) (*Response[apiv0.ServerResponse], error) {
// URL-decode the server name
serverName, err := url.PathUnescape(input.ServerName)
if err != nil {
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
}
// URL-decode the version
version, err := url.PathUnescape(input.Version)
if err != nil {
return nil, huma.Error400BadRequest("Invalid version encoding", err)
}
var serverResponse *apiv0.ServerResponse
// Handle "latest" as a special version
if version == "latest" {
serverResponse, err = registry.GetServerByName(ctx, serverName, input.IncludeDeleted)
} else {
serverResponse, err = registry.GetServerByNameAndVersion(ctx, serverName, version, input.IncludeDeleted)
}
if err != nil {
if err.Error() == errRecordNotFound || errors.Is(err, database.ErrNotFound) {
return nil, huma.Error404NotFound("Server not found")
}
return nil, huma.Error500InternalServerError("Failed to get server details", err)
}
return &Response[apiv0.ServerResponse]{
Body: *serverResponse,
}, nil
})
// Get server versions endpoint
huma.Register(api, huma.Operation{
OperationID: "get-server-versions" + strings.ReplaceAll(pathPrefix, "/", "-"),
Method: http.MethodGet,
Path: pathPrefix + "/servers/{serverName}/versions",
Summary: "Get all versions of an MCP server",
Description: "Get all available versions for a specific MCP server",
Tags: []string{"servers"},
}, func(ctx context.Context, input *ServerVersionsInput) (*Response[apiv0.ServerListResponse], error) {
// URL-decode the server name
serverName, err := url.PathUnescape(input.ServerName)
if err != nil {
return nil, huma.Error400BadRequest("Invalid server name encoding", err)
}
// Get all versions for this server
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")
}
return nil, huma.Error500InternalServerError("Failed to get server versions", err)
}
// Convert []*ServerResponse to []ServerResponse
serverValues := make([]apiv0.ServerResponse, len(servers))
for i, server := range servers {
serverValues[i] = *server
}
return &Response[apiv0.ServerListResponse]{
Body: apiv0.ServerListResponse{
Servers: serverValues,
Metadata: apiv0.Metadata{
Count: len(servers),
},
},
}, nil
})
}