api: Use Huma to generate swagger docs and parse JSON automatically (#262)
## Motivation and Context Currently there's a lot of unsafe manual JSON unmarshalling/marshalling, and we have to manually keep the openapi schema in sync. This PR migrates the API to [Huma](https://github.com/danielgtaylor/huma), which appears like a popular, well-maintained way to build APIs in Golang. I'm not a Golang expert, but seemed highly recommended by Reddit + Claude and has a decent star count. It provides automatic openapi spec generation and docs hosting, JSON parsing, as well as the ability to add auth middlewares etc. ## How Has This Been Tested? Running locally, and poking at the endpoints ## Breaking Changes Docs are served at `/docs` rather than `/v0/swagger/index.html` now ## 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) - [x] New feature (non-breaking change which adds functionality) - [x] Breaking change (fix or feature that would cause existing functionality to change) - [x] Documentation update ## Checklist <!-- Go over all the following points, and put an `x` in all the boxes that apply. --> - [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 ## Additional context <!-- Add any other context, implementation notes, or design decisions -->
This commit is contained in:
parent
122dbf6a68
commit
6b84493ca9
1 changed files with 1622 additions and 2267 deletions
|
|
@ -1,22 +1,15 @@
|
|||
// Package v0 contains API handlers for version 0 of the API
|
||||
package v0
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
"github.com/google/uuid"
|
||||
"github.com/modelcontextprotocol/registry/internal/model"
|
||||
"github.com/modelcontextprotocol/registry/internal/service"
|
||||
)
|
||||
|
||||
// Response is a paginated API response
|
||||
type PaginatedResponse struct {
|
||||
Data []model.Server `json:"servers"`
|
||||
Metadata Metadata `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
// Metadata contains pagination metadata
|
||||
type Metadata struct {
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
|
|
@ -24,107 +17,87 @@ type Metadata struct {
|
|||
Total int `json:"total,omitempty"`
|
||||
}
|
||||
|
||||
// ServersHandler returns a handler for listing registry items
|
||||
func ServersHandler(registry service.RegistryService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
// ListServersInput represents the input for listing servers
|
||||
type ListServersInput struct {
|
||||
Cursor string `query:"cursor" doc:"Pagination cursor (UUID)" format:"uuid" required:"false"`
|
||||
Limit int `query:"limit" doc:"Number of items per page" default:"30" minimum:"1" maximum:"100"`
|
||||
}
|
||||
|
||||
// Parse cursor and limit from query parameters
|
||||
cursor := r.URL.Query().Get("cursor")
|
||||
if cursor != "" {
|
||||
_, err := uuid.Parse(cursor)
|
||||
// ListServersBody represents the paginated server list response body
|
||||
type ListServersBody struct {
|
||||
Servers []model.Server `json:"servers" doc:"List of MCP servers"`
|
||||
Metadata *Metadata `json:"metadata,omitempty" doc:"Pagination metadata"`
|
||||
}
|
||||
|
||||
// ServerDetailInput represents the input for getting server details
|
||||
type ServerDetailInput struct {
|
||||
ID string `path:"id" doc:"Server ID (UUID)" format:"uuid"`
|
||||
}
|
||||
|
||||
|
||||
// RegisterServersEndpoints registers all server-related endpoints
|
||||
func RegisterServersEndpoints(api huma.API, registry service.RegistryService) {
|
||||
// List servers endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "list-servers",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers",
|
||||
Summary: "List MCP servers",
|
||||
Description: "Get a paginated list of MCP servers from the registry",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ListServersInput) (*Response[ListServersBody], error) {
|
||||
// Validate cursor if provided
|
||||
if input.Cursor != "" {
|
||||
_, err := uuid.Parse(input.Cursor)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid cursor parameter", http.StatusBadRequest)
|
||||
return
|
||||
return nil, huma.Error400BadRequest("Invalid cursor parameter")
|
||||
}
|
||||
}
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
|
||||
// Default limit if not specified
|
||||
limit := 30
|
||||
|
||||
// Try to parse limit from query param
|
||||
if limitStr != "" {
|
||||
parsedLimit, err := strconv.Atoi(limitStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid limit parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if limit is within reasonable bounds
|
||||
if parsedLimit <= 0 {
|
||||
http.Error(w, "Limit must be greater than 0", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Cap maximum limit to prevent excessive queries
|
||||
limit = min(parsedLimit, 100)
|
||||
}
|
||||
|
||||
// Use the GetAll method to get paginated results
|
||||
registries, nextCursor, err := registry.List(cursor, limit)
|
||||
// Get paginated results
|
||||
servers, nextCursor, err := registry.List(input.Cursor, input.Limit)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
return nil, huma.Error500InternalServerError("Failed to get registry list", err)
|
||||
}
|
||||
|
||||
// Create paginated response
|
||||
response := PaginatedResponse{
|
||||
Data: registries,
|
||||
// Build response body
|
||||
body := ListServersBody{
|
||||
Servers: servers,
|
||||
}
|
||||
|
||||
|
||||
// Add metadata if there's a next cursor
|
||||
if nextCursor != "" {
|
||||
response.Metadata = Metadata{
|
||||
body.Metadata = &Metadata{
|
||||
NextCursor: nextCursor,
|
||||
Count: len(registries),
|
||||
Count: len(servers),
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ServersDetailHandler returns a handler for getting details of a specific server by ID
|
||||
func ServersDetailHandler(registry service.RegistryService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// Extract the server ID from the URL path
|
||||
id := r.PathValue("id")
|
||||
|
||||
// Validate that the ID is a valid UUID
|
||||
_, err := uuid.Parse(id)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid server ID format", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
return &Response[ListServersBody]{
|
||||
Body: body,
|
||||
}, nil
|
||||
})
|
||||
|
||||
// Get server details endpoint
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "get-server",
|
||||
Method: http.MethodGet,
|
||||
Path: "/v0/servers/{id}",
|
||||
Summary: "Get MCP server details",
|
||||
Description: "Get detailed information about a specific MCP server",
|
||||
Tags: []string{"servers"},
|
||||
}, func(_ context.Context, input *ServerDetailInput) (*Response[model.ServerDetail], error) {
|
||||
// Get the server details from the registry service
|
||||
serverDetail, err := registry.GetByID(id)
|
||||
serverDetail, err := registry.GetByID(input.ID)
|
||||
if err != nil {
|
||||
if err.Error() == "record not found" {
|
||||
http.Error(w, "Server not found", http.StatusNotFound)
|
||||
return
|
||||
return nil, huma.Error404NotFound("Server not found")
|
||||
}
|
||||
http.Error(w, "Error retrieving server details", http.StatusInternalServerError)
|
||||
return
|
||||
return nil, huma.Error500InternalServerError("Failed to get server details", err)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(serverDetail); err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
return &Response[model.ServerDetail]{
|
||||
Body: *serverDetail,
|
||||
}, nil
|
||||
})
|
||||
}
|
||||
Loading…
Reference in a new issue