Module: ZeroMcp::Schema

Defined in:
lib/zeromcp/schema.rb

Constant Summary collapse

TYPE_MAP =
{
  'string'  => { 'type' => 'string' },
  'number'  => { 'type' => 'number' },
  'boolean' => { 'type' => 'boolean' },
  'object'  => { 'type' => 'object' },
  'array'   => { 'type' => 'array' }
}.freeze

Class Method Summary collapse

Class Method Details

.to_json_schema(input) ⇒ Object



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
# File 'lib/zeromcp/schema.rb', line 13

def self.to_json_schema(input)
  return { 'type' => 'object', 'properties' => {}, 'required' => [] } if input.nil? || input.empty?

  properties = {}
  required = []

  input.each do |key, value|
    key = key.to_s
    if value.is_a?(String)
      mapped = TYPE_MAP[value]
      raise "Unknown type \"#{value}\" for field \"#{key}\"" unless mapped

      properties[key] = mapped.dup
      required << key
    elsif value.is_a?(Hash)
      type = value[:type] || value['type']
      mapped = TYPE_MAP[type.to_s]
      raise "Unknown type \"#{type}\" for field \"#{key}\"" unless mapped

      prop = mapped.dup
      desc = value[:description] || value['description']
      prop['description'] = desc if desc
      properties[key] = prop

      optional = value[:optional] || value['optional']
      required << key unless optional
    end
  end

  { 'type' => 'object', 'properties' => properties, 'required' => required }
end

.validate(input, schema) ⇒ Object



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
# File 'lib/zeromcp/schema.rb', line 45

def self.validate(input, schema)
  errors = []

  (schema['required'] || []).each do |key|
    if input[key].nil?
      errors << "Missing required field: #{key}"
    end
  end

  input.each do |key, value|
    prop = schema['properties'][key]
    next unless prop

    actual = value.is_a?(Array) ? 'array' : value.class.name.downcase
    actual = 'number' if value.is_a?(Numeric)
    actual = 'boolean' if value == true || value == false
    actual = 'string' if value.is_a?(String)
    actual = 'object' if value.is_a?(Hash)

    if actual != prop['type']
      errors << "Field \"#{key}\" expected #{prop['type']}, got #{actual}"
    end
  end

  errors
end