ruby-sdk/lib/mcp/annotations.rb
Yuki Minamiya 4c3268ccb1 Add audience role validation for MCP::Annotations per MCP specification
The MCP specification constrains `Annotations.audience` to an array of
`Role` values (`"user"` or `"assistant"`), but the Ruby SDK accepts any
value. The other official SDKs already enforce this (TypeScript, Python,
and PHP).

This follows the existing pattern in `MCP::Icon`, which validates its
constrained `theme` value in the constructor and raises `ArgumentError`.

Added tests in `test/mcp/annotations_test.rb`:

- valid `audience` (`["user"]`, `["assistant"]`, `["user", "assistant"]`,
  and an empty array) is accepted
- an unknown role, a mixed valid/invalid array, or a non-array `audience`
  raises `ArgumentError`

Existing tests used `["developers"]`, which is not a valid `Role`, and are
updated to `["user"]`.

The full unit suite and RuboCop pass locally.

Strictly speaking this is a breaking change: a caller that currently passes
an invalid `audience` (e.g. `["developers"]`) will now get an
`ArgumentError`. Such values already violate the MCP specification, and
`nil` / valid-role values are unaffected.
2026-06-22 01:13:17 +09:00

28 lines
821 B
Ruby

# frozen_string_literal: true
module MCP
class Annotations
SUPPORTED_AUDIENCES = ["user", "assistant"].freeze
attr_reader :audience, :priority, :last_modified
def initialize(audience: nil, priority: nil, last_modified: nil)
if audience && !(audience.is_a?(Array) && audience.all? { |role| SUPPORTED_AUDIENCES.include?(role) })
raise ArgumentError, 'The value of audience must be an array of "user" or "assistant".'
end
raise ArgumentError, "The value of priority must be between 0 and 1." if priority && !priority.between?(0, 1)
@audience = audience
@priority = priority
@last_modified = last_modified
end
def to_h
{
audience: audience,
priority: priority,
lastModified: last_modified,
}.compact
end
end
end