registry/internal/api/handlers/v0/auth.go
Tadas Antanavicius 774a0df592
Add validation tools for server.json schemas and examples (#176)
This is a first PR for #159 - adding some validation scripts. I want to
get to a place where we are confident that making schema changes is in
sync with the rest of our code. Step one is making sure the schemas are
in sync with our examples. Step two will be making sure the schemas are
in sync with our actual Registry implementation code.

This is just for the JSON right now; if we're feeling good about this
approach I'll do an analogous change for the OpenAPI schemas as well.

I'll also follow with adding usage of these scripts to our CI pipeline
so we have automated checks on them with every change.

## Summary
- Added CLI validation tools for JSON schemas and examples in
`docs/server-json/`
- Fixed some minor validation errors found in `examples.md`
- Ensures schema consistency and example validity in CI/CD pipelines

## Changes

### New Validation Tools
1. **`tools/validate-schemas`** - Validates that `schema.json` and
`registry-schema.json` are valid JSON Schema documents
2. **`tools/validate-examples`** - Validates all JSON examples in
`examples.md` against both schemas

### Key Features
- ✅ Validates JSON schema syntax and structure
- ✅ Validates all examples against both base and registry schemas
- ✅ Tracks validation counts to prevent silent failures
- ✅ Proper exit codes for CI integration
- ✅ Clear error messages for debugging

### Fixes to examples.md
- Added missing `repository.id` field in NuGet example
- Changed `repository.source` from "gitlab" to "github" in Docker
example

### Usage
```bash
# From repository root
./tools/validate-schemas.sh
./tools/validate-examples.sh
```

## Testing

I ran these scripts locally with minor (breaking) changes, which they
each correctly reported. As submitted, they are both passing.

🤖 Co-authored with [Claude Code](https://claude.ai/code)

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Charles Lowell <10964656+chlowell@users.noreply.github.com>
2025-07-15 11:32:54 -07:00

126 lines
3.5 KiB
Go

// Package v0 contains API handlers for version 0 of the API
package v0
import (
"encoding/json"
"io"
"net/http"
"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
}
// 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()
// 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
}
// Validate required fields
if authReq.Method == "" {
http.Error(w, "Auth method is required", http.StatusBadRequest)
return
}
// Convert string method to enum type
var method model.AuthMethod
switch authReq.Method {
case "github":
method = model.AuthMethodGitHub
default:
http.Error(w, "Unsupported authentication method", http.StatusBadRequest)
return
}
// Start auth flow
flowInfo, statusToken, err := authService.StartAuthFlow(r.Context(), method, authReq.RepoRef)
if err != nil {
http.Error(w, "Failed to start auth flow: "+err.Error(), http.StatusInternalServerError)
return
}
// 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
}
}
}
// 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)
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
}
// 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
}
}
}