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:
adam jones 2025-08-13 16:57:55 +01:00 • committed by GitHub
commit 6b84493ca9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,126 +1,101 @@
// Package v0 contains API handlers for version 0 of the API
package v0
import (
"encoding/json"
"io"
"context"
"net/http"
"github.com/danielgtaylor/huma/v2"
"github.com/modelcontextprotocol/registry/internal/auth"
"github.com/modelcontextprotocol/registry/internal/model"
)
// StartAuthHandler handles requests to start an authentication flow
func StartAuthHandler(authService auth.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Only allow POST method
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// StartAuthInput represents the input for starting an auth flow
type StartAuthInput struct {
Body struct {
Method string `json:"method" doc:"Authentication method" example:"github"`
RepoRef string `json:"repo_ref" doc:"Repository reference" example:"owner/repo"`
}
}
// Read the request body
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
// StartAuthBody represents the auth flow start response body
type StartAuthBody struct {
AuthFlowInfo map[string]string `json:"auth_flow_info" doc:"Authentication flow information"`
StatusToken string `json:"status_token" doc:"Token to check auth status"`
}
// Parse request body into AuthRequest struct
var authReq struct {
Method string `json:"method"`
RepoRef string `json:"repo_ref"`
}
err = json.Unmarshal(body, &authReq)
if err != nil {
http.Error(w, "Invalid request payload: "+err.Error(), http.StatusBadRequest)
return
}
// CheckAuthStatusInput represents the input for checking auth status
type CheckAuthStatusInput struct {
StatusToken string `path:"token" doc:"Status token from auth flow start"`
}
// CheckAuthStatusBody represents the auth status response body
type CheckAuthStatusBody struct {
Status string `json:"status" doc:"Authentication status" example:"pending"`
}
// RegisterAuthEndpoints registers all auth-related endpoints
func RegisterAuthEndpoints(api huma.API, authService auth.Service) {
// Start auth flow endpoint
huma.Register(api, huma.Operation{
OperationID: "start-auth",
Method: http.MethodPost,
Path: "/v0/auth/start",
Summary: "Start authentication flow",
Description: "Start an authentication flow for publishing servers",
Tags: []string{"auth"},
}, func(ctx context.Context, input *StartAuthInput) (*Response[StartAuthBody], error) {
// Validate required fields
if authReq.Method == "" {
http.Error(w, "Auth method is required", http.StatusBadRequest)
return
if input.Body.Method == "" {
return nil, huma.Error400BadRequest("Auth method is required")
}
if input.Body.RepoRef == "" {
return nil, huma.Error400BadRequest("Repository reference is required")
}
// Convert string method to enum type
var method model.AuthMethod
switch authReq.Method {
// Convert string method to AuthMethod type
var authMethod model.AuthMethod
switch input.Body.Method {
case "github":
method = model.AuthMethodGitHub
authMethod = model.AuthMethodGitHub
case "none":
authMethod = model.AuthMethodNone
default:
http.Error(w, "Unsupported authentication method", http.StatusBadRequest)
return
return nil, huma.Error400BadRequest("Invalid auth method: " + input.Body.Method)
}
// Start auth flow
flowInfo, statusToken, err := authService.StartAuthFlow(r.Context(), method, authReq.RepoRef)
// Start the auth flow
flowInfo, statusToken, err := authService.StartAuthFlow(ctx, authMethod, input.Body.RepoRef)
if err != nil {
http.Error(w, "Failed to start auth flow: "+err.Error(), http.StatusInternalServerError)
return
return nil, huma.Error500InternalServerError("Failed to start auth flow", err)
}
// Return successful response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(map[string]any{
"flow_info": flowInfo,
"status_token": statusToken,
"expires_in": 300, // 5 minutes
}); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
}
}
return &Response[StartAuthBody]{
Body: StartAuthBody{
AuthFlowInfo: flowInfo,
StatusToken: statusToken,
},
}, nil
})
// CheckAuthStatusHandler handles requests to check the status of an authentication flow
func CheckAuthStatusHandler(authService auth.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Only allow GET method
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Get status token from query parameter
statusToken := r.URL.Query().Get("token")
if statusToken == "" {
http.Error(w, "Status token is required", http.StatusBadRequest)
return
}
// Check auth status
token, err := authService.CheckAuthStatus(r.Context(), statusToken)
// Check auth status endpoint
huma.Register(api, huma.Operation{
OperationID: "check-auth-status",
Method: http.MethodGet,
Path: "/v0/auth/status/{token}",
Summary: "Check authentication status",
Description: "Check the status of an ongoing authentication flow",
Tags: []string{"auth"},
}, func(ctx context.Context, input *CheckAuthStatusInput) (*Response[CheckAuthStatusBody], error) {
// Check the auth status
status, err := authService.CheckAuthStatus(ctx, input.StatusToken)
if err != nil {
if err.Error() == "pending" {
// Auth is still pending
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(map[string]any{
"status": "pending",
}); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
return
}
// Other error
http.Error(w, "Failed to check auth status: "+err.Error(), http.StatusInternalServerError)
return
return nil, huma.Error404NotFound("Auth flow not found or expired")
}
// Authentication completed successfully
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(map[string]any{
"status": "complete",
"token": token,
}); err != nil {
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
return
}
}
}
return &Response[CheckAuthStatusBody]{
Body: CheckAuthStatusBody{
Status: status,
},
}, nil
})
}