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
26 changed files with 4153 additions and 474 deletions
|
|
@ -21,8 +21,9 @@ make dev-compose # Start local registry
|
|||
|
||||
### Commands
|
||||
- **`init`** - Generate server.json templates with auto-detection
|
||||
- **`login`** - Handle authentication (github, dns, http, none)
|
||||
- **`login`** - Handle authentication (github, dns, http, none)
|
||||
- **`publish`** - Validate and upload servers to registry
|
||||
- **`status`** - Update server lifecycle status (active, deprecated, deleted)
|
||||
- **`logout`** - Clear stored credentials
|
||||
|
||||
### Authentication Providers
|
||||
|
|
|
|||
375
cmd/publisher/commands/status.go
Normal file
375
cmd/publisher/commands/status.go
Normal file
|
|
@ -0,0 +1,375 @@
|
|||
package commands
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StatusUpdateRequest represents the request body for status update endpoints
|
||||
type StatusUpdateRequest struct {
|
||||
Status string `json:"status"`
|
||||
StatusMessage *string `json:"statusMessage,omitempty"`
|
||||
}
|
||||
|
||||
// AllVersionsStatusResponse represents the response from the all-versions status endpoint
|
||||
type AllVersionsStatusResponse struct {
|
||||
UpdatedCount int `json:"updatedCount"`
|
||||
}
|
||||
|
||||
// VersionInfo holds version and status for display
|
||||
type VersionInfo struct {
|
||||
Version string
|
||||
Status string
|
||||
}
|
||||
|
||||
// ServerResponseMeta represents the _meta field in API responses
|
||||
type ServerResponseMeta struct {
|
||||
Official *struct {
|
||||
Status string `json:"status"`
|
||||
} `json:"io.modelcontextprotocol.registry/official,omitempty"`
|
||||
}
|
||||
|
||||
// SingleServerResponse represents the response from a single server version endpoint
|
||||
type SingleServerResponse struct {
|
||||
Server struct {
|
||||
Version string `json:"version"`
|
||||
} `json:"server"`
|
||||
Meta ServerResponseMeta `json:"_meta"`
|
||||
}
|
||||
|
||||
// ServerListResponse represents the response from the versions list endpoint
|
||||
type ServerListResponse struct {
|
||||
Servers []SingleServerResponse `json:"servers"`
|
||||
}
|
||||
|
||||
func StatusCommand(args []string) error {
|
||||
// Parse command flags
|
||||
fs := flag.NewFlagSet("status", flag.ExitOnError)
|
||||
status := fs.String("status", "", "New status: active, deprecated, or deleted (required)")
|
||||
message := fs.String("message", "", "Optional status message explaining the change")
|
||||
allVersions := fs.Bool("all-versions", false, "Apply status change to all versions of the server")
|
||||
yes := fs.Bool("yes", false, "Skip confirmation prompt for bulk operations")
|
||||
fs.BoolVar(yes, "y", false, "Skip confirmation prompt for bulk operations (shorthand)")
|
||||
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Validate required arguments
|
||||
if *status == "" {
|
||||
return errors.New("--status flag is required (active, deprecated, or deleted)")
|
||||
}
|
||||
|
||||
// Validate status value
|
||||
validStatuses := map[string]bool{"active": true, "deprecated": true, "deleted": true}
|
||||
if !validStatuses[*status] {
|
||||
return fmt.Errorf("invalid status '%s'. Must be one of: active, deprecated, deleted", *status)
|
||||
}
|
||||
|
||||
// Get server name from positional args
|
||||
remainingArgs := fs.Args()
|
||||
if len(remainingArgs) < 1 {
|
||||
return errors.New("server name is required\n\nUsage: mcp-publisher status --status <active|deprecated|deleted> [flags] <server-name> [version]")
|
||||
}
|
||||
|
||||
serverName := remainingArgs[0]
|
||||
var version string
|
||||
|
||||
// Get version if provided (required unless --all-versions is set)
|
||||
if !*allVersions {
|
||||
if len(remainingArgs) < 2 {
|
||||
return errors.New("version is required unless --all-versions flag is set\n\nUsage: mcp-publisher status --status <active|deprecated|deleted> [flags] <server-name> <version>")
|
||||
}
|
||||
version = remainingArgs[1]
|
||||
}
|
||||
|
||||
// Load saved token
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get home directory: %w", err)
|
||||
}
|
||||
|
||||
tokenPath := filepath.Join(homeDir, TokenFileName)
|
||||
tokenData, err := os.ReadFile(tokenPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return errors.New("not authenticated. Run 'mcp-publisher login <method>' first")
|
||||
}
|
||||
return fmt.Errorf("failed to read token: %w", err)
|
||||
}
|
||||
|
||||
var tokenInfo map[string]string
|
||||
if err := json.Unmarshal(tokenData, &tokenInfo); err != nil {
|
||||
return fmt.Errorf("invalid token data: %w", err)
|
||||
}
|
||||
|
||||
token := tokenInfo["token"]
|
||||
registryURL := tokenInfo["registry"]
|
||||
if registryURL == "" {
|
||||
registryURL = DefaultRegistryURL
|
||||
}
|
||||
|
||||
// Update status
|
||||
if *allVersions {
|
||||
return updateAllVersionsStatus(registryURL, serverName, *status, *message, token, *yes)
|
||||
}
|
||||
return updateVersionStatus(registryURL, serverName, version, *status, *message, token)
|
||||
}
|
||||
|
||||
func updateVersionStatus(registryURL, serverName, version, status, statusMessage, token string) error {
|
||||
// Fetch current status to show "from → to"
|
||||
currentStatus, err := fetchVersionStatus(registryURL, serverName, version, token)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch current status: %w", err)
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(os.Stdout, "Updating %s version %s: %s → %s\n", serverName, version, currentStatus, status)
|
||||
|
||||
if err := updateServerStatus(registryURL, serverName, version, status, statusMessage, token); err != nil {
|
||||
return fmt.Errorf("failed to update status: %w", err)
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintln(os.Stdout, "✓ Successfully updated status")
|
||||
return nil
|
||||
}
|
||||
|
||||
func updateAllVersionsStatus(registryURL, serverName, status, statusMessage, token string, skipConfirm bool) error {
|
||||
if !strings.HasSuffix(registryURL, "/") {
|
||||
registryURL += "/"
|
||||
}
|
||||
|
||||
// Fetch all versions to show current statuses and get count for confirmation
|
||||
versions, err := fetchAllVersionsStatus(registryURL, serverName, token)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch current versions: %w", err)
|
||||
}
|
||||
|
||||
if len(versions) == 0 {
|
||||
return errors.New("no versions found for this server")
|
||||
}
|
||||
|
||||
// Show what will be updated
|
||||
_, _ = fmt.Fprintf(os.Stdout, "This will update %d version(s) of %s:\n", len(versions), serverName)
|
||||
for _, v := range versions {
|
||||
_, _ = fmt.Fprintf(os.Stdout, " %s: %s → %s\n", v.Version, v.Status, status)
|
||||
}
|
||||
|
||||
// Prompt for confirmation unless -y/--yes was provided
|
||||
if !skipConfirm {
|
||||
_, _ = fmt.Fprint(os.Stdout, "Continue? [y/N] ")
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
response, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
response = strings.TrimSpace(strings.ToLower(response))
|
||||
if response != "y" && response != "yes" {
|
||||
return errors.New("operation cancelled")
|
||||
}
|
||||
}
|
||||
|
||||
// Build the request body
|
||||
requestBody := StatusUpdateRequest{
|
||||
Status: status,
|
||||
}
|
||||
if statusMessage != "" {
|
||||
requestBody.StatusMessage = &statusMessage
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(requestBody)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error serializing request: %w", err)
|
||||
}
|
||||
|
||||
// URL encode the server name
|
||||
encodedServerName := url.PathEscape(serverName)
|
||||
statusURL := registryURL + "v0/servers/" + encodedServerName + "/status"
|
||||
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPatch, statusURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error sending request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("server returned status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// Parse response to get updated count
|
||||
var response AllVersionsStatusResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
// If we can't parse the response, just report success
|
||||
_, _ = fmt.Fprintln(os.Stdout, "✓ Successfully updated all versions")
|
||||
return nil
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(os.Stdout, "✓ Successfully updated %d version(s)\n", response.UpdatedCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
func updateServerStatus(registryURL, serverName, version, status, statusMessage, token string) error {
|
||||
if !strings.HasSuffix(registryURL, "/") {
|
||||
registryURL += "/"
|
||||
}
|
||||
|
||||
// Build the request body
|
||||
requestBody := StatusUpdateRequest{
|
||||
Status: status,
|
||||
}
|
||||
if statusMessage != "" {
|
||||
requestBody.StatusMessage = &statusMessage
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(requestBody)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error serializing request: %w", err)
|
||||
}
|
||||
|
||||
// URL encode the server name and version
|
||||
encodedServerName := url.PathEscape(serverName)
|
||||
encodedVersion := url.PathEscape(version)
|
||||
statusURL := registryURL + "v0/servers/" + encodedServerName + "/versions/" + encodedVersion + "/status"
|
||||
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPatch, statusURL, bytes.NewBuffer(jsonData))
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error sending request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("server returned status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fetchVersionStatus(registryURL, serverName, version, token string) (string, error) {
|
||||
if !strings.HasSuffix(registryURL, "/") {
|
||||
registryURL += "/"
|
||||
}
|
||||
|
||||
encodedServerName := url.PathEscape(serverName)
|
||||
encodedVersion := url.PathEscape(version)
|
||||
fetchURL := registryURL + "v0/servers/" + encodedServerName + "/versions/" + encodedVersion + "?include_deleted=true"
|
||||
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fetchURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error sending request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error reading response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("server returned status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// Parse the response to extract status
|
||||
var response SingleServerResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
return "", fmt.Errorf("error parsing response: %w", err)
|
||||
}
|
||||
|
||||
if response.Meta.Official == nil {
|
||||
return "", errors.New("server response missing status information")
|
||||
}
|
||||
|
||||
return response.Meta.Official.Status, nil
|
||||
}
|
||||
|
||||
func fetchAllVersionsStatus(registryURL, serverName, token string) ([]VersionInfo, error) {
|
||||
if !strings.HasSuffix(registryURL, "/") {
|
||||
registryURL += "/"
|
||||
}
|
||||
|
||||
encodedServerName := url.PathEscape(serverName)
|
||||
fetchURL := registryURL + "v0/servers/" + encodedServerName + "/versions?include_deleted=true"
|
||||
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fetchURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error creating request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error sending request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error reading response: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("server returned status %d: %s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var response ServerListResponse
|
||||
if err := json.Unmarshal(body, &response); err != nil {
|
||||
return nil, fmt.Errorf("error parsing response: %w", err)
|
||||
}
|
||||
|
||||
var versions []VersionInfo
|
||||
for _, s := range response.Servers {
|
||||
status := "unknown"
|
||||
if s.Meta.Official != nil {
|
||||
status = s.Meta.Official.Status
|
||||
}
|
||||
versions = append(versions, VersionInfo{
|
||||
Version: s.Server.Version,
|
||||
Status: status,
|
||||
})
|
||||
}
|
||||
|
||||
return versions, nil
|
||||
}
|
||||
311
cmd/publisher/commands/status_test.go
Normal file
311
cmd/publisher/commands/status_test.go
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
package commands_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/modelcontextprotocol/registry/cmd/publisher/commands"
|
||||
)
|
||||
|
||||
func TestStatusCommand_Validation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
expectError bool
|
||||
errorSubstr string
|
||||
}{
|
||||
{
|
||||
name: "missing --status flag",
|
||||
args: []string{"io.github.user/my-server", "1.0.0"},
|
||||
expectError: true,
|
||||
errorSubstr: "--status flag is required",
|
||||
},
|
||||
{
|
||||
name: "invalid status value",
|
||||
args: []string{"--status", "invalid", "io.github.user/my-server", "1.0.0"},
|
||||
expectError: true,
|
||||
errorSubstr: "invalid status 'invalid'",
|
||||
},
|
||||
{
|
||||
name: "missing server name",
|
||||
args: []string{"--status", "deprecated"},
|
||||
expectError: true,
|
||||
errorSubstr: "server name is required",
|
||||
},
|
||||
{
|
||||
name: "missing version without --all-versions",
|
||||
args: []string{"--status", "deprecated", "io.github.user/my-server"},
|
||||
expectError: true,
|
||||
errorSubstr: "version is required unless --all-versions",
|
||||
},
|
||||
{
|
||||
name: "valid args passes validation",
|
||||
args: []string{"--status", "deprecated", "io.github.user/my-server", "1.0.0"},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "valid args with --all-versions passes validation",
|
||||
args: []string{"--status", "deprecated", "--all-versions", "io.github.user/my-server"},
|
||||
expectError: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := commands.StatusCommand(tt.args)
|
||||
|
||||
if tt.expectError {
|
||||
if err == nil {
|
||||
t.Errorf("Expected error but got none")
|
||||
return
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.errorSubstr) {
|
||||
t.Errorf("Expected error containing '%s', got: %v", tt.errorSubstr, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
// For valid args, we expect it to pass validation
|
||||
// It may fail later at auth or API level, which is acceptable
|
||||
// Just check it's not a validation error
|
||||
if strings.Contains(err.Error(), "invalid status") ||
|
||||
strings.Contains(err.Error(), "server name is required") ||
|
||||
strings.Contains(err.Error(), "version is required unless") ||
|
||||
strings.Contains(err.Error(), "--status flag is required") {
|
||||
t.Errorf("Validation failed unexpectedly: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCommand_ServerNameValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
serverName string
|
||||
}{
|
||||
{
|
||||
name: "valid github server name",
|
||||
serverName: "io.github.user/my-server",
|
||||
},
|
||||
{
|
||||
name: "valid domain server name",
|
||||
serverName: "com.example/my-server",
|
||||
},
|
||||
{
|
||||
name: "server name with dashes",
|
||||
serverName: "io.github.user/my-cool-server",
|
||||
},
|
||||
{
|
||||
name: "server name with underscores",
|
||||
serverName: "io.github.user/my_server",
|
||||
},
|
||||
{
|
||||
name: "server name with dots",
|
||||
serverName: "io.github.user/my.server",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
args := []string{"--status", "deprecated", tt.serverName, "1.0.0"}
|
||||
err := commands.StatusCommand(args)
|
||||
|
||||
// Should pass validation (server name format is not validated by CLI)
|
||||
if err != nil && strings.Contains(err.Error(), "server name is required") {
|
||||
t.Errorf("Server name '%s' was rejected", tt.serverName)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCommand_VersionValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
version string
|
||||
}{
|
||||
{
|
||||
name: "semver version",
|
||||
version: "1.0.0",
|
||||
},
|
||||
{
|
||||
name: "semver with patch",
|
||||
version: "1.2.3",
|
||||
},
|
||||
{
|
||||
name: "semver with prerelease",
|
||||
version: "1.0.0-alpha",
|
||||
},
|
||||
{
|
||||
name: "semver with build metadata",
|
||||
version: "1.0.0+20130313144700",
|
||||
},
|
||||
{
|
||||
name: "semver with prerelease and build",
|
||||
version: "1.0.0-beta.1+exp.sha.5114f85",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
args := []string{"--status", "deprecated", "io.github.user/my-server", tt.version}
|
||||
err := commands.StatusCommand(args)
|
||||
|
||||
// Should pass validation (version format is not validated by CLI)
|
||||
if err != nil && strings.Contains(err.Error(), "version is required") {
|
||||
t.Errorf("Version '%s' was rejected", tt.version)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCommand_AllVersionsFlag(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
expectError bool
|
||||
errorSubstr string
|
||||
}{
|
||||
{
|
||||
name: "all-versions without version arg passes validation",
|
||||
args: []string{"--status", "deprecated", "--all-versions", "io.github.user/my-server"},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "all-versions with extra version arg still works",
|
||||
args: []string{"--status", "deprecated", "--all-versions", "io.github.user/my-server", "1.0.0"},
|
||||
expectError: false,
|
||||
},
|
||||
{
|
||||
name: "missing server name with all-versions",
|
||||
args: []string{"--status", "deprecated", "--all-versions"},
|
||||
expectError: true,
|
||||
errorSubstr: "server name is required",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := commands.StatusCommand(tt.args)
|
||||
|
||||
if tt.expectError {
|
||||
if err == nil {
|
||||
t.Errorf("Expected error but got none")
|
||||
return
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.errorSubstr) {
|
||||
t.Errorf("Expected error containing '%s', got: %v", tt.errorSubstr, err)
|
||||
}
|
||||
} else if err != nil {
|
||||
// Should pass validation
|
||||
// Just check it's not a validation error
|
||||
if strings.Contains(err.Error(), "invalid status") ||
|
||||
strings.Contains(err.Error(), "server name is required") ||
|
||||
strings.Contains(err.Error(), "version is required unless") ||
|
||||
strings.Contains(err.Error(), "--status flag is required") {
|
||||
t.Errorf("Validation failed unexpectedly: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCommand_FlagCombinations(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{
|
||||
name: "status with message",
|
||||
args: []string{"--status", "deprecated", "--message", "Please upgrade to v2", "io.github.user/my-server", "1.0.0"},
|
||||
},
|
||||
{
|
||||
name: "all-versions with message",
|
||||
args: []string{"--status", "deprecated", "--all-versions", "--message", "All versions deprecated", "io.github.user/my-server"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := commands.StatusCommand(tt.args)
|
||||
// All these should pass CLI validation
|
||||
// They may fail at auth or API level which is acceptable
|
||||
if err != nil {
|
||||
// Just check it's not a validation error we can detect
|
||||
if strings.Contains(err.Error(), "invalid status") ||
|
||||
strings.Contains(err.Error(), "server name is required") ||
|
||||
strings.Contains(err.Error(), "version is required unless") ||
|
||||
strings.Contains(err.Error(), "--status flag is required") {
|
||||
t.Errorf("Validation failed unexpectedly: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCommand_MissingStatus(t *testing.T) {
|
||||
// Test various ways status flag can be missing
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{
|
||||
name: "no status flag at all",
|
||||
args: []string{"io.github.user/my-server", "1.0.0"},
|
||||
},
|
||||
{
|
||||
name: "empty status value",
|
||||
args: []string{"--status", "", "io.github.user/my-server", "1.0.0"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := commands.StatusCommand(tt.args)
|
||||
|
||||
if err == nil {
|
||||
t.Errorf("Expected error for missing status but got none")
|
||||
return
|
||||
}
|
||||
if !strings.Contains(err.Error(), "--status flag is required") {
|
||||
t.Errorf("Expected '--status flag is required' error, got: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCommand_YesFlag(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{
|
||||
name: "all-versions with --yes flag",
|
||||
args: []string{"--status", "deprecated", "--all-versions", "--yes", "io.github.user/my-server"},
|
||||
},
|
||||
{
|
||||
name: "all-versions with -y shorthand",
|
||||
args: []string{"--status", "deprecated", "--all-versions", "-y", "io.github.user/my-server"},
|
||||
},
|
||||
{
|
||||
name: "yes flag with single version (flag accepted but not used)",
|
||||
args: []string{"--status", "deprecated", "--yes", "io.github.user/my-server", "1.0.0"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := commands.StatusCommand(tt.args)
|
||||
// All these should pass CLI validation
|
||||
// They may fail at auth or API level which is acceptable
|
||||
if err != nil {
|
||||
// Just check it's not a validation error
|
||||
if strings.Contains(err.Error(), "invalid status") ||
|
||||
strings.Contains(err.Error(), "server name is required") ||
|
||||
strings.Contains(err.Error(), "version is required unless") ||
|
||||
strings.Contains(err.Error(), "--status flag is required") ||
|
||||
strings.Contains(err.Error(), "flag provided but not defined") {
|
||||
t.Errorf("Validation failed unexpectedly: %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -43,6 +43,8 @@ func main() {
|
|||
err = commands.LogoutCommand()
|
||||
case "publish":
|
||||
err = commands.PublishCommand(os.Args[2:])
|
||||
case "status":
|
||||
err = commands.StatusCommand(os.Args[2:])
|
||||
case "validate":
|
||||
err = commands.ValidateCommand(os.Args[2:])
|
||||
case "--version", "-v", "version":
|
||||
|
|
@ -73,6 +75,7 @@ func printUsage() {
|
|||
_, _ = fmt.Fprintln(os.Stdout, " login Authenticate with the registry")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " logout Clear saved authentication")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " publish Publish server.json to the registry")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " status Update the status of a server version")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " validate Validate server.json without publishing")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, "Use 'mcp-publisher <command> --help' for more information about a command.")
|
||||
|
|
@ -128,6 +131,39 @@ func printCommandHelp(command string) {
|
|||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, "You must be logged in before publishing. Run 'mcp-publisher login' first.")
|
||||
|
||||
case "status":
|
||||
_, _ = fmt.Fprintln(os.Stdout, "Update the status of a server version")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, "Usage:")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " mcp-publisher status --status <active|deprecated|deleted> [flags] <server-name> [version]")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, "Flags (must come before positional arguments):")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " --status string New status: active, deprecated, or deleted (required)")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " --message string Optional message explaining the status change")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " --all-versions Apply status change to all versions of the server")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, "Arguments:")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " server-name Full server name (e.g., io.github.user/my-server)")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " version Server version to update (required unless --all-versions is set)")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, "Examples:")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " # Deprecate a specific version")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " mcp-publisher status --status deprecated --message \"Please upgrade to 2.0.0\" \\")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " io.github.user/my-server 1.0.0")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, " # Delete a version with security issues")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " mcp-publisher status --status deleted --message \"Critical security vulnerability\" \\")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " io.github.user/my-server 1.0.0")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, " # Restore a version to active")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " mcp-publisher status --status active io.github.user/my-server 1.0.0")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, " # Deprecate all versions")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " mcp-publisher status --status deprecated --all-versions --message \"Project archived\" \\")
|
||||
_, _ = fmt.Fprintln(os.Stdout, " io.github.user/my-server")
|
||||
_, _ = fmt.Fprintln(os.Stdout)
|
||||
_, _ = fmt.Fprintln(os.Stdout, "You must be logged in before updating status. Run 'mcp-publisher login' first.")
|
||||
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "Unknown command: %s\n", command)
|
||||
printUsage()
|
||||
|
|
|
|||
|
|
@ -18,7 +18,21 @@ sidebarTitle: FAQ
|
|||
|
||||
### Can I delete/unpublish my server?
|
||||
|
||||
Currently, no. At the time of writing, there is [open discussion](https://github.com/modelcontextprotocol/registry/issues/104).
|
||||
Yes, you can change your server's status to `deleted` using the `mcp-publisher status` command:
|
||||
|
||||
```bash
|
||||
# Delete a specific version
|
||||
mcp-publisher status --status deleted --message "No longer maintained" \
|
||||
io.github.my-username/my-server 1.0.0
|
||||
|
||||
# Delete all versions
|
||||
mcp-publisher status --status deleted --all-versions --message "Project archived" \
|
||||
io.github.my-username/my-server
|
||||
```
|
||||
|
||||
Deleted servers are hidden from default API listings but can still be retrieved with `include_deleted=true`. You can restore a deleted server by setting its status back to `active`.
|
||||
|
||||
**Note**: Server metadata is never permanently removed from the registry. The `deleted` status hides the server from discovery but preserves the historical record.
|
||||
|
||||
### How do I update my server metadata?
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,39 @@
|
|||
|
||||
Changes to the REST API endpoints and responses.
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
|
||||
#### Server Status Management Endpoints
|
||||
|
||||
New endpoints for managing server lifecycle status:
|
||||
|
||||
- `PATCH /v0/servers/{serverName}/versions/{version}/status` - Update status of a specific server version
|
||||
- `PATCH /v0/servers/{serverName}/status` - Update status of all versions of a server in a single transaction
|
||||
|
||||
**Status values:**
|
||||
- `active` - Server is active and visible in default listings
|
||||
- `deprecated` - Server is deprecated but still visible with a warning message
|
||||
- `deleted` - Server is hidden from default listings
|
||||
|
||||
**Authentication:** Requires `publish` or `edit` permission for the server namespace.
|
||||
|
||||
#### New Response Fields
|
||||
|
||||
New fields added to `_meta["io.modelcontextprotocol.registry/official"]` (RegistryExtensions):
|
||||
|
||||
- `statusChangedAt` - Timestamp when the server status was last changed
|
||||
- `statusMessage` - Optional message explaining status change (e.g., deprecation reason, migration guidance)
|
||||
|
||||
#### Server Filtering Enhancements
|
||||
|
||||
New `include_deleted` query parameter added to multiple endpoints:
|
||||
|
||||
- `GET /v0/servers` - Include deleted servers in list results (default: `false`, automatically `true` when `updated_since` is provided)
|
||||
- `GET /v0/servers/{serverName}/versions/{version}` - Include deleted servers in detail results (default: `false`)
|
||||
- `GET /v0/servers/{serverName}/versions` - Include deleted servers in version history (default: `false`)
|
||||
|
||||
## 2025-10-17
|
||||
|
||||
### Added
|
||||
|
|
@ -120,4 +153,4 @@ API endpoints updated for consistent server identification across versions.
|
|||
|
||||
## 2025-07-09
|
||||
|
||||
Initial release of the Registry API.
|
||||
Initial release of the Registry API.
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ The official registry has some more endpoints and restrictions on top of this. S
|
|||
- **`POST /v0.1/publish`** - Publish new server (optional, registry-specific authentication)
|
||||
- **`PUT /v0.1/servers/{serverName}/versions/{version}`** - Update specific server version (optional, not implemented by official registry)
|
||||
- **`DELETE /v0.1/servers/{serverName}/versions/{version}`** - Delete specific server version (optional, not implemented by official registry)
|
||||
- **`PATCH /v0.1/servers/{serverName}/versions/{version}/status`** - Update server version status (optional)
|
||||
- **`PATCH /v0.1/servers/{serverName}/status`** - Update status for all versions (optional)
|
||||
|
||||
Server names and version strings should be URL-encoded in paths.
|
||||
|
||||
|
|
|
|||
|
|
@ -38,14 +38,36 @@ The official registry enforces additional [package validation requirements](../s
|
|||
The official registry extends the `GET /v0.1/servers` endpoint with additional query parameters for improved discovery and synchronization:
|
||||
|
||||
- `updated_since` - Filter servers updated after RFC3339 timestamp (e.g., `2025-08-07T13:15:04.280Z`)
|
||||
- `search` - Case-insensitive substring search on server names (e.g., `filesystem`)
|
||||
- `search` - Case-insensitive substring search on server names (e.g., `filesystem`)
|
||||
- This is intentionally simple. For more advanced searching and filtering, use a subregistry.
|
||||
- `version` - Filter by version (currently supports `latest` for latest versions only)
|
||||
- `include_deleted` - Include deleted servers in results (default: `false`, but automatically `true` when `updated_since` is provided for incremental sync)
|
||||
|
||||
These extensions enable efficient incremental synchronization for downstream registries and improved server discovery. Parameters can be combined and work with standard cursor-based pagination.
|
||||
|
||||
Example: `GET /v0.1/servers?search=filesystem&updated_since=2025-08-01T00:00:00Z&version=latest`
|
||||
|
||||
### Server Detail
|
||||
|
||||
The `GET /v0.1/servers/{serverName}/versions/{version}` endpoint returns detailed information about a specific server version.
|
||||
|
||||
**Path parameters:**
|
||||
- `serverName` - URL-encoded server name (e.g., `io.github.user%2Fmy-server`)
|
||||
- `version` - Server version or `latest` for the most recent version
|
||||
|
||||
**Query parameters:**
|
||||
- `include_deleted` - Include deleted servers in results (default: `false`)
|
||||
|
||||
### Server Version History
|
||||
|
||||
The `GET /v0.1/servers/{serverName}/versions` endpoint returns all versions of a server.
|
||||
|
||||
**Path parameters:**
|
||||
- `serverName` - URL-encoded server name (e.g., `io.github.user%2Fmy-server`)
|
||||
|
||||
**Query parameters:**
|
||||
- `include_deleted` - Include deleted servers in results (default: `false`)
|
||||
|
||||
### Additional endpoints
|
||||
|
||||
#### Auth endpoints
|
||||
|
|
@ -55,6 +77,38 @@ Example: `GET /v0.1/servers?search=filesystem&updated_since=2025-08-01T00:00:00Z
|
|||
- POST `/v0.1/auth/github-oidc` - Exchange GitHub OIDC token for auth token
|
||||
- POST `/v0.1/auth/oidc` - Exchange Google OIDC token for auth token (for admins)
|
||||
|
||||
#### Status endpoints
|
||||
|
||||
##### Update Single Version Status
|
||||
|
||||
`PATCH /v0.1/servers/{serverName}/versions/{version}/status` - Update status of a specific server version.
|
||||
|
||||
**Path parameters:**
|
||||
- `serverName` - URL-encoded server name (e.g., `io.github.user%2Fmy-server`)
|
||||
- `version` - Server version to update
|
||||
|
||||
**Request body:**
|
||||
- `status` (required) - New status: `active`, `deprecated`, or `deleted`
|
||||
- `statusMessage` (optional) - Message explaining the status change (max 500 characters, not allowed when status is `active`)
|
||||
|
||||
##### Update All Versions Status
|
||||
|
||||
`PATCH /v0.1/servers/{serverName}/status` - Update status of all versions of a server in a single transaction.
|
||||
|
||||
**Path parameters:**
|
||||
- `serverName` - URL-encoded server name (e.g., `io.github.user%2Fmy-server`)
|
||||
|
||||
**Request body:**
|
||||
- `status` (required) - New status: `active`, `deprecated`, or `deleted`
|
||||
- `statusMessage` (optional) - Message explaining the status change (max 500 characters, not allowed when status is `active`)
|
||||
|
||||
**Status values:**
|
||||
- `active` - Server is active and visible in default listings
|
||||
- `deprecated` - Server is deprecated but still visible with a warning message
|
||||
- `deleted` - Server is hidden from default listings (use `include_deleted=true` to show)
|
||||
|
||||
**Authentication:** Requires `publish` or `edit` permission for the server namespace.
|
||||
|
||||
#### Admin endpoints
|
||||
- GET `/metrics` - Prometheus metrics endpoint
|
||||
- GET `/v0.1/health` - Basic health check endpoint
|
||||
|
|
|
|||
|
|
@ -61,6 +61,13 @@ paths:
|
|||
schema:
|
||||
type: string
|
||||
example: "1.2.3"
|
||||
- name: include_deleted
|
||||
in: query
|
||||
description: Include deleted servers in results (default false, but always true when updated_since is provided)
|
||||
required: false
|
||||
schema:
|
||||
type: boolean
|
||||
default: false
|
||||
responses:
|
||||
'200':
|
||||
description: A list of MCP servers
|
||||
|
|
@ -307,6 +314,156 @@ paths:
|
|||
error:
|
||||
type: string
|
||||
example: "Deletion is not supported by this registry"
|
||||
/v0.1/servers/{serverName}/versions/{version}/status:
|
||||
patch:
|
||||
tags: [publish]
|
||||
summary: Update server version status
|
||||
description: |
|
||||
Update the lifecycle status of a specific server version.
|
||||
|
||||
Requires `publish` or `edit` permission for the server namespace.
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- name: serverName
|
||||
in: path
|
||||
required: true
|
||||
description: URL-encoded server name (e.g., "com.example%2Fmy-server")
|
||||
schema:
|
||||
type: string
|
||||
example: "com.example%2Fmy-server"
|
||||
- name: version
|
||||
in: path
|
||||
required: true
|
||||
description: URL-encoded version to update
|
||||
schema:
|
||||
type: string
|
||||
example: "1.0.0"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/StatusUpdateRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully updated server status
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ServerResponse'
|
||||
'400':
|
||||
description: Bad request - Invalid status transition or no changes to apply
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "No changes to apply: status is already deprecated"
|
||||
'401':
|
||||
description: Unauthorized - Invalid or missing authentication token
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Invalid or expired Registry JWT token"
|
||||
'403':
|
||||
description: Forbidden - Insufficient permissions
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "You do not have publish or edit permissions for this server"
|
||||
'404':
|
||||
description: Server version not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Server version not found"
|
||||
/v0.1/servers/{serverName}/status:
|
||||
patch:
|
||||
tags: [publish]
|
||||
summary: Update status for all server versions
|
||||
description: |
|
||||
Update the lifecycle status of all versions of a server in a single transaction.
|
||||
Either all versions are updated or none on failure.
|
||||
|
||||
Requires `publish` or `edit` permission for the server namespace.
|
||||
security:
|
||||
- bearerAuth: []
|
||||
parameters:
|
||||
- name: serverName
|
||||
in: path
|
||||
required: true
|
||||
description: URL-encoded server name (e.g., "com.example%2Fmy-server")
|
||||
schema:
|
||||
type: string
|
||||
example: "com.example%2Fmy-server"
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/StatusUpdateRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: Successfully updated all versions
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AllVersionsStatusResponse'
|
||||
'400':
|
||||
description: Bad request - Invalid status value
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Invalid status value"
|
||||
'401':
|
||||
description: Unauthorized - Invalid or missing authentication token
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Invalid or expired Registry JWT token"
|
||||
'403':
|
||||
description: Forbidden - Insufficient permissions
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "You do not have publish or edit permissions for this server"
|
||||
'404':
|
||||
description: Server not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error:
|
||||
type: string
|
||||
example: "Server not found"
|
||||
/v0.1/publish:
|
||||
post:
|
||||
tags: [publish]
|
||||
|
|
@ -863,6 +1020,11 @@ components:
|
|||
enum: ["active", "deprecated", "deleted"]
|
||||
description: Server lifecycle status
|
||||
example: "active"
|
||||
statusMessage:
|
||||
type: string
|
||||
description: Optional message explaining the status (e.g., deprecation reason)
|
||||
example: "Please upgrade to version 2.0.0"
|
||||
maxLength: 500
|
||||
publishedAt:
|
||||
type: string
|
||||
format: date-time
|
||||
|
|
@ -879,3 +1041,37 @@ components:
|
|||
example: true
|
||||
additionalProperties: false
|
||||
additionalProperties: true
|
||||
|
||||
StatusUpdateRequest:
|
||||
description: Request body for updating server status
|
||||
type: object
|
||||
required:
|
||||
- status
|
||||
properties:
|
||||
status:
|
||||
type: string
|
||||
enum: ["active", "deprecated", "deleted"]
|
||||
description: New server lifecycle status
|
||||
example: "deprecated"
|
||||
statusMessage:
|
||||
type: string
|
||||
description: Optional message explaining the status change (e.g., deprecation reason)
|
||||
example: "Please upgrade to version 2.0.0"
|
||||
maxLength: 500
|
||||
|
||||
AllVersionsStatusResponse:
|
||||
description: Response from bulk status update for all versions
|
||||
type: object
|
||||
required:
|
||||
- updatedCount
|
||||
- servers
|
||||
properties:
|
||||
updatedCount:
|
||||
type: integer
|
||||
description: Number of versions updated
|
||||
example: 3
|
||||
servers:
|
||||
type: array
|
||||
description: List of all updated server versions
|
||||
items:
|
||||
$ref: '#/components/schemas/ServerResponse'
|
||||
|
|
|
|||
|
|
@ -276,6 +276,51 @@ mcp-publisher publish
|
|||
mcp-publisher publish ./config/server.json
|
||||
```
|
||||
|
||||
### `mcp-publisher status`
|
||||
|
||||
Update the lifecycle status of a published server.
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
mcp-publisher status --status <active|deprecated|deleted> [flags] <server-name> [version]
|
||||
```
|
||||
|
||||
**Flags:**
|
||||
- `--status` (required) - New status: `active`, `deprecated`, or `deleted`
|
||||
- `--message` - Optional message explaining the status change (not allowed when status is `active`)
|
||||
- `--all-versions` - Apply status change to all versions of the server
|
||||
- `--yes`, `-y` - Skip confirmation prompt (only applies when using `--all-versions`)
|
||||
|
||||
**Arguments:**
|
||||
- `server-name` - Full server name (e.g., `io.github.user/my-server`)
|
||||
- `version` - Server version to update (required unless `--all-versions` is set)
|
||||
|
||||
**Status Values:**
|
||||
- `active` - Server is active and visible in default listings
|
||||
- `deprecated` - Server is deprecated but still visible with a warning message
|
||||
- `deleted` - Server is hidden from default listings
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
# Deprecate a specific version
|
||||
mcp-publisher status --status deprecated --message "Please upgrade to 2.0.0" \
|
||||
io.github.user/my-server 1.0.0
|
||||
|
||||
# Delete a version with security issues
|
||||
mcp-publisher status --status deleted --message "Critical security vulnerability" \
|
||||
io.github.user/my-server 1.0.0
|
||||
|
||||
# Restore a version to active
|
||||
mcp-publisher status --status active io.github.user/my-server 1.0.0
|
||||
|
||||
# Deprecate all versions at once
|
||||
mcp-publisher status --status deprecated --all-versions --message "Project archived" \
|
||||
io.github.user/my-server
|
||||
```
|
||||
|
||||
**Requirements:**
|
||||
- Must be logged in with `publish` or `edit` permission for the server namespace
|
||||
|
||||
### `mcp-publisher logout`
|
||||
|
||||
Clear stored authentication credentials.
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue