Skip to content

Commit bee7308

Browse files
committed
refactor: share tool schema validation helpers
1 parent 9d2fdd0 commit bee7308

4 files changed

Lines changed: 23 additions & 16 deletions

File tree

lib/mcp/tool.rb

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -93,23 +93,29 @@ def icons(value = NOT_SET)
9393
def input_schema(value = NOT_SET)
9494
if value == NOT_SET
9595
input_schema_value
96-
elsif value.is_a?(Hash)
97-
@input_schema_value = InputSchema.new(value)
98-
elsif value.is_a?(InputSchema)
99-
@input_schema_value = value
96+
elsif (schema = coerce_schema(value, InputSchema))
97+
@input_schema_value = schema
10098
end
10199
end
102100

103101
def output_schema(value = NOT_SET)
104102
if value == NOT_SET
105103
output_schema_value
106-
elsif value.is_a?(Hash)
107-
@output_schema_value = OutputSchema.new(value)
108-
elsif value.is_a?(OutputSchema)
109-
@output_schema_value = value
104+
elsif (schema = coerce_schema(value, OutputSchema))
105+
@output_schema_value = schema
110106
end
111107
end
112108

109+
def coerce_schema(value, schema_class)
110+
case value
111+
when Hash
112+
schema_class.new(value)
113+
when schema_class
114+
value
115+
end
116+
end
117+
private :coerce_schema
118+
113119
def meta(value = NOT_SET)
114120
if value == NOT_SET
115121
@meta_value

lib/mcp/tool/input_schema.rb

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,7 @@ def missing_required_arguments(arguments)
1818
end
1919

2020
def validate_arguments(arguments)
21-
errors = fully_validate(arguments)
22-
if errors.any?
23-
raise ValidationError, "Invalid arguments: #{errors.join(", ")}"
24-
end
21+
validate_payload!(arguments, "arguments")
2522
end
2623
end
2724
end

lib/mcp/tool/output_schema.rb

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ class OutputSchema < Schema
88
class ValidationError < StandardError; end
99

1010
def validate_result(result)
11-
errors = fully_validate(result)
12-
if errors.any?
13-
raise ValidationError, "Invalid result: #{errors.join(", ")}"
14-
end
11+
validate_payload!(result, "result")
1512
end
1613
end
1714
end

lib/mcp/tool/schema.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ def to_h
3131

3232
private
3333

34+
def validate_payload!(payload, label)
35+
errors = fully_validate(payload)
36+
if errors.any?
37+
raise self.class::ValidationError, "Invalid #{label}: #{errors.join(", ")}"
38+
end
39+
end
40+
3441
def fully_validate(data)
3542
JSON::Validator.fully_validate(schema_for_validation, data)
3643
end

0 commit comments

Comments
 (0)