registry/internal/validators/registries/npm.go
adam jones 694a4d8879
Add registry validators (#350)
Fixes #96

## Motivation and Context

See #96

## How Has This Been Tested?

Has some unit and integration tests, still needs proper testing of the
different registry types

## Breaking Changes

Yes, new package uploads will need extra verification

## 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)
- [ ] Documentation update
2025-09-04 22:45:59 +01:00

66 lines
2 KiB
Go

package registries
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/modelcontextprotocol/registry/pkg/model"
)
// NPMPackageResponse represents the structure returned by the NPM registry API
type NPMPackageResponse struct {
MCPName string `json:"mcpName"`
}
// ValidateNPM validates that an NPM package contains the correct MCP server name
func ValidateNPM(ctx context.Context, pkg model.Package, serverName string) error {
// Set default registry base URL if empty
if pkg.RegistryBaseURL == "" {
pkg.RegistryBaseURL = model.RegistryURLNPM
}
// Validate that the registry base URL matches NPM exactly
if pkg.RegistryBaseURL != model.RegistryURLNPM {
return fmt.Errorf("registry type and base URL do not match: '%s' is not valid for registry type '%s'. Expected: %s",
pkg.RegistryBaseURL, model.RegistryTypeNPM, model.RegistryURLNPM)
}
client := &http.Client{Timeout: 10 * time.Second}
url := pkg.RegistryBaseURL + "/" + pkg.Identifier + "/" + pkg.Version
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("User-Agent", "MCP-Registry-Validator/1.0")
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to fetch package metadata from NPM: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("NPM package '%s' not found (status: %d)", pkg.Identifier, resp.StatusCode)
}
var npmResp NPMPackageResponse
if err := json.NewDecoder(resp.Body).Decode(&npmResp); err != nil {
return fmt.Errorf("failed to parse NPM package metadata: %w", err)
}
if npmResp.MCPName == "" {
return fmt.Errorf("NPM package '%s' is missing required 'mcpName' field. Add this to your package.json: \"mcpName\": \"%s\"", pkg.Identifier, serverName)
}
if npmResp.MCPName != serverName {
return fmt.Errorf("NPM package ownership validation failed. Expected mcpName '%s', got '%s'", serverName, npmResp.MCPName)
}
return nil
}