registry/internal/api/handlers/v0/servers.go
Radoslav Dimitrov 1a7cd97099
Introduce v0.1 version of the API (#658)
<!-- Provide a brief summary of your changes -->

## Motivation and Context
<!-- Why is this change needed? What problem does it solve? -->
The following PR adds a new v0.1 API version. 

The goal is to mark v0.1 as a "freeze" point while keeping v0 as the
moving target for new features so integrators can start building on top
of something stable(r).

Details:
* This change is quite simple - we re-register the same handlers twice,
once as `v0` and once as `v0.1`
* Going forward, we'll keep v0.1 frozen while we add changes either on
top of both (non-breaking) or we'll have to branch if breaking changes
are necessary
* We all acknowledge this is not exactly best-practice, but it gives us
a way to gather feedback and allow clients to start integrating with the
API without breaking them (**note** this implies a follow up PR that
would branch the handlers used in v0.1).
* For integrators/clients: please provide your feedback - what works
well, what doesn't so we can take this into account going towards GA.

## How Has This Been Tested?
<!-- Have you tested this in a real application? Which scenarios were
tested? -->

## Breaking Changes
<!-- Will users need to update their code or configurations? -->
No, this just adds a new API version alongside the existing one.

## Types of changes
<!-- What types of changes does your code introduce? Put an `x` in all
the boxes that apply: -->
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update

## Checklist
<!-- Go over all the following points, and put an `x` in all the boxes
that apply. -->
- [ ] I have read the [MCP
Documentation](https://modelcontextprotocol.io)
- [ ] My code follows the repository's style guidelines
- [ ] New and existing tests pass locally
- [ ] I have added appropriate error handling
- [ ] I have added or updated documentation as needed

## Additional context
<!-- Add any other context, implementation notes, or design decisions
-->
Fixes: #649

Signed-off-by: Radoslav Dimitrov <radoslav@stacklok.com>
2025-10-14 11:04:48 +03:00

187 lines
6.8 KiB
Go

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