-
Notifications
You must be signed in to change notification settings - Fork 977
Expand file tree
/
Copy pathschema.go
More file actions
587 lines (528 loc) · 19.1 KB
/
Copy pathschema.go
File metadata and controls
587 lines (528 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
package validators
import (
"bytes"
"embed"
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"unicode/utf8"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/modelcontextprotocol/registry/pkg/model"
"github.com/santhosh-tekuri/jsonschema/v5"
)
//go:embed schemas/*.json
var schemaFS embed.FS
// extractVersionFromSchemaURL extracts the version identifier from a schema URL
// e.g., "https://static.modelcontextprotocol.io/schemas/2025-10-17/server.schema.json" -> "2025-10-17"
// e.g., "https://static.modelcontextprotocol.io/schemas/draft/server.schema.json" -> "draft"
// Version identifier can contain: A-Z, a-z, 0-9, hyphen (-), underscore (_), tilde (~), and period (.)
func extractVersionFromSchemaURL(schemaURL string) (string, error) {
// Pattern: /schemas/{identifier}/server.schema.json
// Identifier allowed characters: A-Z, a-z, 0-9, -, _, ~, .
re := regexp.MustCompile(`/schemas/([A-Za-z0-9_~.-]+)/server\.schema\.json`)
matches := re.FindStringSubmatch(schemaURL)
if len(matches) < 2 {
return "", fmt.Errorf("invalid schema URL format: %s", schemaURL)
}
return matches[1], nil
}
// loadSchemaByVersion loads a schema file from the embedded filesystem by version
func loadSchemaByVersion(version string) ([]byte, error) {
filename := fmt.Sprintf("schemas/%s.json", version)
data, err := schemaFS.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("schema version %s not found in embedded schemas: %w", version, err)
}
return data, nil
}
// GetCurrentSchemaVersion returns the current schema URL from constants
func GetCurrentSchemaVersion() (string, error) {
return model.CurrentSchemaURL, nil
}
// validateServerJSONSchema validates the server JSON against the schema version specified in $schema using jsonschema
// Empty/missing schema always produces an error.
// If performValidation is true, performs full JSON Schema validation.
// If performValidation is false, only checks for empty schema (always an error) and handles non-current schemas per policy.
// nonCurrentPolicy determines how non-current (but valid) schema versions are handled when performValidation is true.
func validateServerJSONSchema(serverJSON *apiv0.ServerJSON, performValidation bool, nonCurrentPolicy SchemaVersionPolicy) *ValidationResult {
result := &ValidationResult{Valid: true, Issues: []ValidationIssue{}}
ctx := &ValidationContext{}
// Empty/missing schema is always an error
if serverJSON.Schema == "" {
issue := NewValidationIssue(
ValidationIssueTypeSemantic,
ctx.Field("schema").String(),
"$schema field is required",
ValidationIssueSeverityError,
"schema-field-required",
)
result.AddIssue(issue)
return result
}
// Extract version from the schema URL
version, err := extractVersionFromSchemaURL(serverJSON.Schema)
if err != nil {
issue := NewValidationIssue(
ValidationIssueTypeSchema,
ctx.Field("schema").String(),
fmt.Sprintf("failed to extract schema version from URL: %v", err),
ValidationIssueSeverityError,
"schema-version-extraction-error",
)
result.AddIssue(issue)
return result
}
// Check if the schema version is the current one and handle based on policy
currentSchemaURL, err := GetCurrentSchemaVersion()
if err == nil && serverJSON.Schema != currentSchemaURL {
// Extract current version for the message
currentVersion, _ := extractVersionFromSchemaURL(currentSchemaURL)
switch nonCurrentPolicy {
case SchemaVersionPolicyError:
issue := NewValidationIssue(
ValidationIssueTypeSemantic,
ctx.Field("schema").String(),
fmt.Sprintf("schema version %s is not the current version (%s). Use the current schema version", version, currentVersion),
ValidationIssueSeverityError,
"schema-version-deprecated",
)
result.AddIssue(issue)
case SchemaVersionPolicyWarn:
issue := NewValidationIssue(
ValidationIssueTypeSemantic,
ctx.Field("schema").String(),
fmt.Sprintf("schema version %s is not the current version (%s). Consider updating to the latest schema version", version, currentVersion),
ValidationIssueSeverityWarning,
"schema-version-deprecated",
)
result.AddIssue(issue)
case SchemaVersionPolicyAllow:
// No issue added - allow non-current schemas silently
}
}
// Load the appropriate schema file to verify it exists (required for schema version validation)
// This ensures that the specified schema version is available, even when not performing full validation
schemaData, err := loadSchemaByVersion(version)
if err != nil {
issue := NewValidationIssue(
ValidationIssueTypeSchema,
ctx.Field("schema").String(),
fmt.Sprintf("schema version %s not available: %v", version, err),
ValidationIssueSeverityError,
"schema-version-not-available",
)
result.AddIssue(issue)
return result
}
// If not performing validation, return after performing schema version checks (done above)
if !performValidation {
return result
}
// Parse the schema
var schema map[string]any
if err := json.Unmarshal(schemaData, &schema); err != nil {
// If we can't parse the schema, return an error
issue := NewValidationIssue(
ValidationIssueTypeSchema,
ctx.Field("schema").String(),
fmt.Sprintf("failed to parse schema file: %v", err),
ValidationIssueSeverityError,
"schema-parse-error",
)
result.AddIssue(issue)
return result
}
// Convert the server JSON to a map for validation
serverData, err := json.Marshal(serverJSON)
if err != nil {
issue := NewValidationIssue(
ValidationIssueTypeJSON,
"",
fmt.Sprintf("failed to marshal server JSON for schema validation: %v", err),
ValidationIssueSeverityError,
"json-marshal-error",
)
result.AddIssue(issue)
return result
}
var serverMap map[string]any
if err := json.Unmarshal(serverData, &serverMap); err != nil {
issue := NewValidationIssue(
ValidationIssueTypeJSON,
"",
fmt.Sprintf("failed to unmarshal server JSON for schema validation: %v", err),
ValidationIssueSeverityError,
"json-unmarshal-error",
)
result.AddIssue(issue)
return result
}
// Get the schema $id for proper reference resolution
// Schema files must have $id (required by JSON Schema spec and verified by sync process)
// However, we check here in case a schema file exists but is malformed or missing $id
schemaID, ok := schema["$id"].(string)
if !ok {
issue := NewValidationIssue(
ValidationIssueTypeSchema,
ctx.Field("schema").String(),
fmt.Sprintf("schema file for version %s exists but is missing or has invalid $id field (required by JSON Schema spec)", version),
ValidationIssueSeverityError,
"schema-missing-id",
)
result.AddIssue(issue)
return result
}
// Validate against schema using jsonschema library
compiler := jsonschema.NewCompiler()
if err := compiler.AddResource(schemaID, bytes.NewReader(schemaData)); err != nil {
// If we can't add the schema resource, return an error
issue := NewValidationIssue(
ValidationIssueTypeSchema,
ctx.Field("schema").String(),
fmt.Sprintf("failed to add schema resource: %v", err),
ValidationIssueSeverityError,
"schema-resource-error",
)
result.AddIssue(issue)
return result
}
schemaInstance, err := compiler.Compile(schemaID)
if err != nil {
// If we can't compile the schema, return an error
issue := NewValidationIssue(
ValidationIssueTypeSchema,
"",
fmt.Sprintf("failed to compile schema: %v", err),
ValidationIssueSeverityError,
"schema-compile-error",
)
result.AddIssue(issue)
return result
}
// Perform validation
if err := schemaInstance.Validate(serverMap); err != nil {
// Convert validation error to our issue format
var validationErr *jsonschema.ValidationError
if errors.As(err, &validationErr) {
// Process the validation error and its causes
addValidationError(result, validationErr, schema, serverMap)
} else {
// Fallback for other error types
issue := NewValidationIssue(
ValidationIssueTypeSchema,
"",
fmt.Sprintf("schema validation failed: %v", err),
ValidationIssueSeverityError,
"schema-validation-error",
)
result.AddIssue(issue)
}
}
return result
}
// addValidationError processes validation errors and extracts useful information
func addValidationError(result *ValidationResult, validationErr *jsonschema.ValidationError, schema map[string]any, instance any) {
// Use DetailedOutput to get the nested error details
detailed := validationErr.DetailedOutput()
// Process the detailed error structure
addDetailedErrors(result, detailed, schema, instance)
}
// ConvertJSONPointerToBracketNotation converts a JSON Pointer path (RFC 6901) to bracket notation
// format to match the format used by semantic validation (ValidationContext).
// The transformation includes:
// 1. Remove leading slash from JSON Pointer format
// 2. Convert path separators from "/" to "."
// 3. Convert numeric array indices from dot notation to bracket notation
// Example: "/packages/0/transport" -> "packages[0].transport"
// Example: "/0/name" -> "[0].name"
// Example: "/packages/0/transport/1/url" -> "packages[0].transport[1].url"
func ConvertJSONPointerToBracketNotation(jsonPointer string) string {
if jsonPointer == "" {
return ""
}
// Step 1: Convert JSON Pointer to dot notation (remove leading slash, convert / to .)
path := strings.TrimPrefix(jsonPointer, "/")
path = strings.ReplaceAll(path, "/", ".")
// Step 2: Convert dot notation array indices to bracket notation
if path == "" {
return ""
}
parts := strings.Split(path, ".")
var result strings.Builder
for i, part := range parts {
// Check if part is a pure number (array index)
if _, err := strconv.Atoi(part); err == nil {
// It's a numeric index - use bracket notation
fmt.Fprintf(&result, "[%s]", part)
// Add dot after bracket if next part exists and is a field name (not a number)
if i < len(parts)-1 {
nextPart := parts[i+1]
if _, err := strconv.Atoi(nextPart); err != nil {
// Next part is a field name, add dot separator
result.WriteString(".")
}
// If next part is a number, no dot needed (brackets will connect: [0][1])
}
} else {
// It's a field name
// Add dot separator before field name if previous part was also a field name
if i > 0 {
prevPart := parts[i-1]
if _, err := strconv.Atoi(prevPart); err != nil {
// Previous was not a number (it's a field), need dot separator
result.WriteString(".")
}
// If previous was a number, brackets already written, dot added after bracket above
}
result.WriteString(part)
}
}
return result.String()
}
// addDetailedErrors recursively processes detailed validation errors
func addDetailedErrors(result *ValidationResult, detailed jsonschema.Detailed, schema map[string]any, instance any) {
// Only process errors that have specific field paths and meaningful messages
if detailed.InstanceLocation != "" && detailed.Error != "" {
// Convert JSON Pointer format to bracket notation to match semantic validation format
path := ConvertJSONPointerToBracketNotation(detailed.InstanceLocation)
// Clean up the error message
message := detailed.Error
// Make messages more user-friendly
if strings.Contains(message, "missing properties:") {
message = strings.ReplaceAll(message, "missing properties:", "missing required fields:")
}
if strings.Contains(message, "is not valid") {
message = strings.ReplaceAll(message, "is not valid", "has invalid format")
}
// Provide explicit feedback for maxLength violations: name the field, show the
// observed/max length, and suggest a truncated value the publisher can paste back.
// Issue: https://github.com/modelcontextprotocol/registry/issues/1184
if enhanced, ok := enhanceMaxLengthMessage(detailed, instance, path); ok {
message = enhanced
}
// Build the full resolved reference path
reference := buildResolvedReference(detailed.KeywordLocation, detailed.AbsoluteKeywordLocation, schema)
issue := NewValidationIssue(
ValidationIssueTypeSchema,
path,
message,
ValidationIssueSeverityError,
reference, // cleaned schema rule path for deterministic mapping
)
result.AddIssue(issue)
}
// Process nested errors
for _, nested := range detailed.Errors {
addDetailedErrors(result, nested, schema, instance)
}
}
// maxLengthErrorRe matches the jsonschema library's default maxLength error message,
// which is formatted as "length must be <= MAX, but got OBSERVED". Captures: 1=max, 2=observed.
var maxLengthErrorRe = regexp.MustCompile(`length must be <= (\d+), but got (\d+)`)
// enhanceMaxLengthMessage rewrites the jsonschema library's terse maxLength error message
// into something publishers can act on directly: it names the field, reports the observed
// length, restates the limit, and includes a truncated value they can paste back. Returns
// false if the error is not a maxLength violation or the offending value cannot be resolved.
func enhanceMaxLengthMessage(detailed jsonschema.Detailed, instance any, bracketPath string) (string, bool) {
if !strings.HasSuffix(detailed.KeywordLocation, "/maxLength") {
return "", false
}
matches := maxLengthErrorRe.FindStringSubmatch(detailed.Error)
if len(matches) != 3 {
return "", false
}
maxLen, err := strconv.Atoi(matches[1])
if err != nil {
return "", false
}
value, ok := resolveJSONPointer(instance, detailed.InstanceLocation)
if !ok {
return "", false
}
str, ok := value.(string)
if !ok {
return "", false
}
fieldName := extractFieldName(bracketPath)
observed := utf8.RuneCountInString(str)
suggestion := truncateForSuggestion(str, maxLen)
return fmt.Sprintf(`field %q is too long: %d chars (max %d). Truncate to: %q`,
fieldName, observed, maxLen, suggestion), true
}
// resolveJSONPointer walks a decoded JSON value (map[string]any / []any) following an
// RFC 6901 JSON Pointer and returns the value at that location. Returns false if the
// pointer cannot be resolved.
func resolveJSONPointer(data any, pointer string) (any, bool) {
if pointer == "" {
return data, true
}
if !strings.HasPrefix(pointer, "/") {
return nil, false
}
current := data
for _, raw := range strings.Split(pointer[1:], "/") {
// RFC 6901 escape sequences: ~1 -> "/", ~0 -> "~" (~1 must come first)
token := strings.ReplaceAll(raw, "~1", "/")
token = strings.ReplaceAll(token, "~0", "~")
switch node := current.(type) {
case map[string]any:
next, exists := node[token]
if !exists {
return nil, false
}
current = next
case []any:
idx, err := strconv.Atoi(token)
if err != nil || idx < 0 || idx >= len(node) {
return nil, false
}
current = node[idx]
default:
return nil, false
}
}
return current, true
}
// extractFieldName returns the leaf field name from a bracket-notation path, so e.g.
// "packages[0].description" -> "description" and "packages[0]" -> "packages".
func extractFieldName(path string) string {
if path == "" {
return ""
}
if idx := strings.LastIndex(path, "."); idx != -1 {
path = path[idx+1:]
}
if idx := strings.Index(path, "["); idx != -1 {
path = path[:idx]
}
return path
}
// truncateForSuggestion returns a rune-safe truncation of s that fits within maxLen
// characters, ending in an ellipsis "..." when truncation is needed. For maxLen <= 3
// (no room for an ellipsis) it returns the first maxLen runes verbatim.
func truncateForSuggestion(s string, maxLen int) string {
if maxLen <= 0 {
return ""
}
runes := []rune(s)
if len(runes) <= maxLen {
return s
}
const ellipsis = "..."
if maxLen <= len(ellipsis) {
return string(runes[:maxLen])
}
return string(runes[:maxLen-len(ellipsis)]) + ellipsis
}
// buildResolvedReference extracts the resolved reference path by resolving $ref segments
func buildResolvedReference(keywordLocation, absoluteKeywordLocation string, schema map[string]any) string {
if keywordLocation == "" || absoluteKeywordLocation == "" {
return ""
}
// Clean up the absolute location by removing file:// prefix
absolute := absoluteKeywordLocation
if strings.HasPrefix(absolute, "file://") {
absolute = strings.TrimPrefix(absolute, "file://")
if idx := strings.Index(absolute, "#"); idx != -1 {
absolute = absolute[idx:] // Keep only the #/path part
}
}
// Parse the keyword location to understand the $ref chain
keyword := strings.TrimPrefix(keywordLocation, "/")
keywordParts := strings.Split(keyword, "/")
// Build the path showing $ref resolution
pathSegments := make([]string, 0)
// Track the resolved path so far (starts empty, gets built up as we resolve $refs)
resolvedPath := ""
// Process each part of the keyword path
for i, part := range keywordParts {
if part == "" {
continue // Skip empty parts
}
if part == "$ref" {
// This is a $ref - we need to look up what it resolves to
// For the first $ref, use the path from the root
// For subsequent $refs, use the resolved path from the previous $ref plus the current segment
var refPath string
if resolvedPath == "" {
// First $ref - use the path from the root
refPath = strings.Join(keywordParts[:i+1], "/")
refPath = "/" + refPath
} else {
// Subsequent $ref - use the resolved path plus the current segment
refPath = resolvedPath + "/" + part
}
// Look up the $ref value in the schema
refValue := resolveRefInSchema(schema, refPath)
if refValue != "" {
pathSegments = append(pathSegments, fmt.Sprintf("[%s]", refValue))
// Update the resolved path for the next $ref
resolvedPath = refValue
} else {
pathSegments = append(pathSegments, "[$ref]")
}
} else {
// Regular path segment
pathSegments = append(pathSegments, part)
// Add this segment to the resolved path for the next $ref
if resolvedPath != "" {
resolvedPath = resolvedPath + "/" + part
} else {
resolvedPath = part
}
}
}
// Build the final reference string
if len(pathSegments) > 0 {
pathStr := strings.Join(pathSegments, "/")
return fmt.Sprintf("%s from: %s", absolute, pathStr)
}
// Fallback: return the absolute location with context
return absolute + " (from: " + keywordLocation + ")"
}
// resolveRefInSchema looks up a $ref value in the schema
func resolveRefInSchema(schema map[string]any, refPath string) string {
// Handle the # prefix - it indicates the root of the schema JSON
refPath = strings.TrimPrefix(refPath, "#")
// Parse the JSON pointer path
pathParts := strings.Split(strings.TrimPrefix(refPath, "/"), "/")
// Navigate through the schema to find the $ref value
var current any = schema
for _, part := range pathParts {
if part == "" {
continue
}
if part == "$ref" {
// We've reached the $ref, return its value
if currentMap, ok := current.(map[string]any); ok {
if refValue, ok := currentMap["$ref"].(string); ok {
return refValue
}
}
return ""
}
// Navigate to the next level
// Check if this is an array index
if index, err := strconv.Atoi(part); err == nil {
// This is an array index - check if current element is an array
if arr, ok := current.([]any); ok && index < len(arr) {
current = arr[index]
} else {
// Current element is not an array or index out of bounds
return ""
}
} else {
// This is a map key
if currentMap, ok := current.(map[string]any); ok {
current = currentMap[part]
} else {
// Current element is not a map
return ""
}
}
}
return ""
}