Skip to content

[go-fan] google/jsonschema-go #14739

@github-actions

Description

@github-actions

🐹 Go Fan Report: google/jsonschema-go

Module Overview

github.com/google/jsonschema-go is an official Google project implementing the JSON Schema specification for Go. It's a zero-dependency library created in August 2025 that provides automatic JSON schema generation from Go struct types using generics. The library supports JSON Schema draft 2020-12 and draft-07, enabling type-safe schema inference, validation, and construction.

Status: ✅ Up to date - Using v0.4.2 (latest, released Dec 19, 2025)

Current Usage in gh-aw

Primary Use Case: Schema generation for MCP (Model Context Protocol) server implementation

The project follows an excellent architectural pattern using TWO JSON schema libraries, each specialized for its purpose:

  • google/jsonschema-go → Schema generation (Go structs → JSON Schema)
  • santhosh-tekuri/jsonschema/v6 → Schema validation (data against schemas)

Files: 3 implementation files, 3 test files

  • pkg/cli/mcp_schema.go - Core schema generation helpers
  • pkg/cli/mcp_server.go - MCP tool schema generation with elicitation defaults
  • Comprehensive test coverage in mcp_schema_test.go and mcp_server_defaults_test.go

Key APIs Used:

// Type-safe schema generation using Go generics
schema, err := jsonschema.For[MyStruct](nil)

// Adding elicitation defaults for better UX (SEP-1024)
AddSchemaDefault(schema, "strict", true)
AddSchemaDefault(schema, "count", 100)

// Schema validation (in tests)
resolved, err := schema.Resolve(&jsonschema.ResolveOptions{})
err = resolved.Validate(jsonValue)

Research Findings

Repository Health

  • Stars: 313
  • 📅 Created: August 2025 (relatively new but actively maintained)
  • 🔄 Last Updated: February 10, 2026 (this week!)
  • 📜 License: MIT (permissive)
  • 📦 Dependencies: Zero - only uses Go standard library

Recent Updates (v0.4.0 - December 2025)

The most recent major release brought several valuable features:

  1. Draft 07 Support - Now supports both JSON Schema draft 2020-12 and draft-07, improving compatibility
  2. PropertyOrder Feature - Maintains deterministic field ordering for consistent schema generation (important for diffs/versioning)
  3. Improved Nullable Handling - Arrays and slices now correctly include null in their type array by default
  4. Nested Subschema Defaults - Proper application of defaults in nested structures
  5. Bug Fixes - Various improvements for embedded structs, custom schemas, and edge cases

Best Practices from Maintainers

  1. Validation Target: Always validate JSON values (maps/slices), not Go structs directly
  2. Descriptions: Use jsonschema: struct tags generously - helps LLMs understand schemas
  3. Required vs Optional: Use omitempty/omitzero tags to mark optional fields
  4. Defaults: Must manually set defaults after generation (no struct tag support)
  5. Resolution: Call schema.Resolve() before validation to prepare schema

Improvement Opportunities

✨ Feature Opportunities

  1. Leverage Validation Constraints (v0.4.0+)

    The library now supports validation constraints through struct tags that we could leverage in MCP tool parameters:

    type logsArgs struct {
        Count   int `json:"count" jsonschema:"Number of runs,minimum=1,maximum=1000"`
        Timeout int `json:"timeout" jsonschema:"Max seconds,minimum=1,maximum=300"`
    }

    Benefit: Adds server-side validation hints to MCP clients, improving parameter validation before execution.

  2. Format Annotations for Better Semantics

    Add format annotations for fields with specific formats:

    jsonschema:"format=date-time"  // For timestamps
    jsonschema:"format=uri"         // For URLs
  3. Schema Reuse with $ref

    For repeated structures like WorkflowStatus or LogsData, could generate shared definitions using $ref to reduce schema size.

🏃 Quick Wins

  1. Remove Deprecated Function

    GenerateOutputSchema() in pkg/cli/mcp_schema.go:38-42 is marked deprecated and just calls GenerateSchema(). Can be safely removed - only used in tests.

  2. Enhance Error Handling

    Current code logs schema generation errors but continues:

    // pkg/cli/mcp_server.go:270-273
    compileSchema, err := GenerateSchema[compileArgs]()
    if err != nil {
        mcpLog.Printf("Failed to generate compile tool schema: %v", err)
        return nil  // Consider more prominent error handling
    }

    Schema generation errors indicate struct tag or type issues that should fail fast.

  3. Add Meta-Schema Validation in Tests

    Tests generate schemas but don't validate that generated schemas are valid JSON Schema documents. Could add validation against JSON Schema meta-schema.

📐 Best Practice Alignment

EXCELLENT - The project follows best practices exceptionally well:

  • Schema Descriptions: Every field has jsonschema: tags for LLM understanding
  • Required Fields: Correct use of omitempty tags
  • Default Values: Clean implementation of elicitation defaults (SEP-1024)
  • Type Safety: Leverages generics for compile-time type safety
  • Library Selection: Smart use of specialized libraries (generation vs validation)

🔧 General Improvements

  1. ForOptions Exploration

    Currently always calls jsonschema.For[T](nil). The library supports ForOptions for customization:

    • ForOptions.TypeSchemas - Custom schemas for specific types
    • Could be useful for time.Duration or custom enums
  2. Schema Caching

    Schemas are regenerated on every MCP server startup. Since they only change when code changes, could cache them for minor performance gain.

  3. PropertyOrder Verification

    Since v0.4.0 added PropertyOrder, should verify field ordering is deterministic and matches expectations (important for schema versioning).

  4. Document Draft Version

    The library supports both draft 2020-12 and draft-07. Should document which draft version MCP clients expect.

Comparative Analysis: Why Two JSON Schema Libraries?

The project's use of two libraries is actually a smart architectural decision:

Library Purpose Strengths
google/jsonschema-go Schema generation Zero dependencies, type-safe generics, official Google project, excellent struct tag support
santhosh-tekuri/jsonschema/v6 Schema validation Mature (2017), full draft support, performance optimized, comprehensive errors

Why not consolidate? Each library excels at its specific task. Using one for both would compromise either type-safety (generation) or validation features (validation). The clean separation of concerns is excellent architecture.

Recommendations

✅ High Priority - Current Usage is Excellent!

The project uses this library idiomatically and appropriately. No urgent changes needed.

Enhancements to consider:

  1. Add Validation Constraints - Leverage v0.4.0's constraint features for better MCP tool parameter validation
  2. Remove Deprecated Function - Clean up GenerateOutputSchema()
  3. Document Schema Draft Version - Clarify which JSON Schema draft is targeted

💡 Medium Priority

  1. Explore ForOptions for custom type schemas
  2. Add meta-schema validation tests
  3. Verify PropertyOrder behavior is as expected

🎯 Low Priority

  1. Consider schema caching for minor performance gain
  2. Investigate $ref usage if schemas grow large

Next Steps

This module is well-utilized and represents a good example of:

  • Appropriate library selection
  • Clean, idiomatic usage
  • Following best practices
  • Staying current with updates

Action Items: None urgent. Consider the enhancements listed above as the project evolves, particularly validation constraints which would add value to the MCP tool parameter definitions.

References


Note: This was intended to be a discussion, but discussions could not be created due to permissions issues. This issue was created as a fallback.

AI generated by Go Fan

  • expires on Feb 17, 2026, 7:29 AM UTC

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions