Conform Tool Schemas to JSON Schema 2020-12 per SEP-2106

## Motivation and Context

SEP-2106 (modelcontextprotocol/modelcontextprotocol#2106, merged for the 2026-07-28 spec release)
makes tool `inputSchema` and `outputSchema` conform to the full JSON Schema 2020-12 vocabulary:
an input schema keeps `type: "object"` at the root but may use any 2020-12 keyword below it;
an output schema may be ANY valid schema (object, array, primitive, or a root-level composition);
and `CallToolResult.structuredContent` widens from an object to any JSON value. The SEP also adds
resource bounds: `$ref` resolution is restricted (same-document only in the reference implementation) and
composition-heavy documents must be bounded to avoid excessive validation cost.

This follows the TypeScript SDK's reference implementation (typescript-sdk#2249; the Python SDK tracks
the same work in python-sdk#2792):

- `Tool::Schema` now validates against the JSON Schema 2020-12 metaschema rather than the draft-04 metaschema.
  The draft-04 pin was a stopgap from when the SDK used the `json-schema` gem, which did not support 2020-12;
  `json_schemer` does, so `$defs`/`$ref` and the rest of the 2020-12 vocabulary now resolve natively.
  This matches the dialect the SDK already advertises in emitted schemas and the Python SDK's behavior,
   whose `jsonschema.validate` selects the validator from the schema's `$schema`.
- `Tool::Schema` moves root-type defaulting into an overridable `apply_default_root_type!` hook.
  `InputSchema` keeps the historical `type: "object"` default; `OutputSchema` now applies it only
  when no root schema keyword (`type`, `$ref`, `oneOf`, `anyOf`, `allOf`, `not`, `if`, `const`, `enum`) is present.
  The previous unconditional default merged `type: "object"` into root combinators such as `{ oneOf: [...] }`,
  producing a wrong schema, so that case is a bug fix.
- `Tool::Schema` enforces the TypeScript SDK's schema bounds at construction time: only same-document
  `$ref`/`$dynamicRef`s (starting with `#`, so schema handling can never trigger network or file access),
  `MAX_SCHEMA_DEPTH = 64` nesting levels, and `MAX_SUBSCHEMA_COUNT = 10_000` subschema objects,
  all raising `ArgumentError` on violation.
- `Server#call_tool` mirrors non-object `structuredContent` into `content` as serialized JSON text
  when the tool provided no content blocks, so pre-SEP clients that only read `content` still receive the data.
  Object results and explicit content are untouched.

Resolves #377.

## How Has This Been Tested?

- `test/mcp/tool/output_schema_test.rb`: root-level `oneOf`, `$ref`+`$defs`, primitive, and `enum` schemas serialize
  without an injected `type` and validate results correctly; the `properties`-only shorthand still serializes
  with `type: "object"` (wire-format regression); explicit `type: "array"` keeps working.
- `test/mcp/tool/input_schema_test.rb`: an input schema using `$defs`, `$ref`, `oneOf`, `if`/`then`, and `allOf`
  keeps its object root and round-trips all keywords; a draft-04-only boolean `exclusiveMinimum` is rejected
  under the 2020-12 dialect while the numeric form is accepted.
- `test/mcp/tool/schema_test.rb`: depth and subschema-count bound violations raise `ArgumentError`;
  non-same-document `$ref`s (remote URI, sibling file) are rejected while `#/$defs/...` is accepted.
  The previous unbounded-depth caching test is replaced, since the depth bound now rejects such documents by design.
- `test/mcp/server_test.rb`: `tools/call` with array `structuredContent` and no content gains
  the serialized TextContent fallback; explicit content is not overwritten; object `structuredContent` gets no fallback.

`bundle exec rake` (tests, RuboCop, and conformance baseline, including the `json-schema-2020-12` server scenario) passes.

## Breaking Changes

Three narrow behavior changes, all intentional per the SEP:

- Runtime validation now uses the JSON Schema 2020-12 metaschema instead of draft-04.
  Schemas that rely on draft-04-only syntax are rejected at construction time. The practical case is the boolean
  `exclusiveMinimum`/`exclusiveMaximum` form (deprecated since draft-06), which must now be the numeric form;
  the Python SDK rejects it the same way. Other draft-04 spellings (`definitions`, `id`, `dependencies`) still validate,
  since 2020-12 tolerates unknown keywords.
- Schemas that exceed the new resource bounds (nesting deeper than 64, more than 10,000 subschema objects) or
  use a non-same-document `$ref`/`$dynamicRef` now raise `ArgumentError` at construction time.
  Previously such documents were accepted (external references were already never fetched, only ignored).
- An `OutputSchema` whose root declares a schema keyword other than `type` (e.g. `oneOf`) no longer has  `type: "object"`
  merged into it. The old output was an invalid hybrid schema, so no conforming consumer could have relied on it.
This commit is contained in:
Koichi ITO 2026-06-19 09:42:57 +09:00
commit 5ca8b6ebbb
4 changed files with 303 additions and 25 deletions

View file

@ -2884,6 +2884,58 @@ module MCP
end
end
test "#handle tools/call mirrors non-object structuredContent into serialized text content" do
# Per SEP-2106, `structuredContent` may be any JSON value. Older clients may only read `content`,
# so the server adds a serialized fallback when the tool provided no content blocks.
server = Server.new(name: "structured_test", tools: [])
server.define_tool(name: "array_tool") do
Tool::Response.new(nil, structured_content: [1, 2])
end
response = server.handle({
jsonrpc: "2.0",
method: "tools/call",
id: 1,
params: { name: "array_tool", arguments: {} },
})
assert_equal [1, 2], response.dig(:result, :structuredContent)
assert_equal [{ type: "text", text: "[1,2]" }], response.dig(:result, :content)
end
test "#handle tools/call does not overwrite explicit content when structuredContent is non-object" do
server = Server.new(name: "structured_test", tools: [])
server.define_tool(name: "array_tool") do
Tool::Response.new([{ type: "text", text: "two items" }], structured_content: [1, 2])
end
response = server.handle({
jsonrpc: "2.0",
method: "tools/call",
id: 1,
params: { name: "array_tool", arguments: {} },
})
assert_equal [{ type: "text", text: "two items" }], response.dig(:result, :content)
end
test "#handle tools/call leaves object structuredContent without a text fallback" do
server = Server.new(name: "structured_test", tools: [])
server.define_tool(name: "object_tool") do
Tool::Response.new(nil, structured_content: { answer: 42 })
end
response = server.handle({
jsonrpc: "2.0",
method: "tools/call",
id: 1,
params: { name: "object_tool", arguments: {} },
})
assert_equal({ answer: 42 }, response.dig(:result, :structuredContent))
assert_empty response.dig(:result, :content)
end
test "#handle tools/list returns paginated results when page_size is set" do
tool_a = Tool.define(name: "tool_a", title: "Tool A", description: "Tool A")
tool_b = Tool.define(name: "tool_b", title: "Tool B", description: "Tool B")

View file

@ -101,6 +101,22 @@ module MCP
end
end
test "rejects a draft-04-only boolean exclusiveMinimum under the 2020-12 dialect" do
# SEP-2106 validates tool schemas against the JSON Schema 2020-12 metaschema,
# where `exclusiveMinimum` must be a number. The draft-04 boolean form (deprecated since draft-06)
# is rejected at construction, matching the Python SDK's `jsonschema` validator selection.
error = assert_raises(ArgumentError) do
InputSchema.new(properties: { age: { type: "integer", minimum: 0, exclusiveMinimum: true } })
end
assert_includes error.message, "Invalid JSON Schema"
end
test "accepts the 2020-12 numeric exclusiveMinimum form" do
assert_nothing_raised do
InputSchema.new(properties: { age: { type: "integer", exclusiveMinimum: 0 } })
end
end
test "schema without required arguments is valid" do
assert_nothing_raised do
InputSchema.new(properties: { foo: { type: "string" } })
@ -183,6 +199,26 @@ module MCP
assert_equal "#/definitions/bar", schema.to_h[:properties][:foo][:$ref]
end
test "keeps the object root type while accepting 2020-12 composition keywords" do
# Per SEP-2106, an input schema root must stay `type: "object"` but may use
# the full 2020-12 vocabulary below the root.
schema = InputSchema.new(
"$defs": { name: { type: "string", minLength: 1 } },
properties: {
name: { "$ref": "#/$defs/name" },
value: { oneOf: [{ type: "string" }, { type: "integer" }] },
},
if: { properties: { value: { type: "integer" } } },
then: { required: ["name"] },
allOf: [{ properties: { extra: { type: "boolean" } } }],
)
assert_equal "object", schema.to_h[:type]
assert schema.to_h.key?(:"$defs")
assert schema.to_h.key?(:if)
assert schema.to_h.key?(:allOf)
end
test "== compares two input schemas with the same properties, required fields" do
schema1 = InputSchema.new(properties: { foo: { type: "string" } }, required: ["foo"])
schema2 = InputSchema.new(properties: { foo: { type: "string" } }, required: ["foo"])

View file

@ -215,6 +215,51 @@ module MCP
end
end
test "does not inject a root type into a root-level oneOf schema" do
# Per SEP-2106, an output schema may be any JSON Schema 2020-12 document.
# Merging `type: "object"` into a root combinator would produce a wrong schema.
schema = OutputSchema.new(oneOf: [{ type: "string" }, { type: "integer" }])
refute schema.to_h.key?(:type)
assert_equal [{ type: "string" }, { type: "integer" }], schema.to_h[:oneOf]
assert_nothing_raised { schema.validate_result("text") }
assert_nothing_raised { schema.validate_result(42) }
assert_raises(OutputSchema::ValidationError) { schema.validate_result(1.5) }
end
test "does not inject a root type into a root-level $ref schema" do
schema = OutputSchema.new(
"$ref": "#/$defs/result",
"$defs": { result: { type: "string" } },
)
refute schema.to_h.key?(:type)
assert_nothing_raised { schema.validate_result("text") }
assert_raises(OutputSchema::ValidationError) { schema.validate_result(42) }
end
test "allows primitive root schemas" do
schema = OutputSchema.new(type: "string")
assert_nothing_raised { schema.validate_result("text") }
assert_raises(OutputSchema::ValidationError) { schema.validate_result(42) }
end
test "does not inject a root type into a root-level enum schema" do
schema = OutputSchema.new(enum: ["red", "green", "blue"])
refute schema.to_h.key?(:type)
assert_nothing_raised { schema.validate_result("red") }
assert_raises(OutputSchema::ValidationError) { schema.validate_result("yellow") }
end
test "defaults a properties-only schema to a root object" do
# Wire-format regression: the common shorthand keeps serializing with the injected `type: "object"`.
schema = OutputSchema.new(properties: { result: { type: "string" } })
assert_equal "object", schema.to_h[:type]
end
test "allow to declare array schemas" do
schema = OutputSchema.new({
type: "array",

View file

@ -51,24 +51,58 @@ module MCP
assert_raises(ArgumentError) { InputSchema.new(invalid) }
end
test "a schema at the normalization depth limit is cached without a nesting error" do
# The deepest schema the initializer can still normalize via JSON.dump/parse.
# The cache key must tolerate the same depth; the default JSON.generate
# nesting limit (100) is stricter than normalization and would raise here.
schema = { properties: { leaf: { type: "string" } } }
loop do
candidate = { properties: { child: schema } }
JSON.parse(JSON.dump(candidate))
schema = candidate
rescue JSON::NestingError
break
test "a schema nested deeper than MAX_SCHEMA_DEPTH raises" do
# SEP-2106 resource bounds: unbounded nesting would make downstream validation arbitrarily expensive.
# Each wrapping adds two levels (the schema hash and its `properties` hash), so this is the smallest
# nesting that exceeds MAX_SCHEMA_DEPTH.
wrappings = Schema::MAX_SCHEMA_DEPTH / 2 + 1
schema = { type: "string" }
wrappings.times do
schema = { type: "object", properties: { child: schema } }
end
JSONSchemer::Schema.any_instance.stubs(:validate_schema).returns([])
error = assert_raises(ArgumentError) { InputSchema.new(schema) }
assert_match(/maximum depth/, error.message)
end
test "a schema with more subschema objects than MAX_SUBSCHEMA_COUNT raises" do
properties = {}
(Schema::MAX_SUBSCHEMA_COUNT + 1).times do |i|
properties[:"property_#{i}"] = { type: "string" }
end
error = assert_raises(ArgumentError) { InputSchema.new(properties: properties) }
assert_match(/subschema/, error.message)
end
test "rejects a $ref pointing outside the schema document" do
# SEP-2106 requires same-document `$ref` resolution only; a remote URI or a sibling file must never trigger network
# or file access.
error = assert_raises(ArgumentError) do
InputSchema.new(properties: { foo: { "$ref": "https://example.com/schema.json#/defs/bar" } })
end
assert_match(/same-document/, error.message)
assert_raises(ArgumentError) do
InputSchema.new(properties: { foo: { "$ref": "other.json#/defs/bar" } })
end
end
test "rejects a $dynamicRef pointing outside the schema document" do
# 2020-12 allows `$dynamicRef` to carry an absolute URI too, so the same-document restriction must cover it as well as `$ref`.
error = assert_raises(ArgumentError) do
InputSchema.new(properties: { foo: { "$dynamicRef": "https://example.com/schema.json#meta" } })
end
assert_match(/same-document/, error.message)
assert_match(/\$dynamicRef/, error.message)
end
test "accepts a same-document $ref" do
assert_nothing_raised do
InputSchema.new(schema)
InputSchema.new(schema)
InputSchema.new(
"$defs": { bar: { type: "string" } },
properties: { foo: { "$ref": "#/$defs/bar" } },
)
end
end