Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 81 additions & 12 deletions lib/mcp/resource_template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ class ResourceTemplate
class << self
NOT_SET = Object.new

# Applied after `Regexp.escape`, which turns `{` and `}` into `\{` and `\}`.
# Variable names are restricted to valid Regexp named-group names,
# so RFC 6570 operator expressions (e.g. `{?query}`) stay literal and never match.
VARIABLE_PATTERN = /\\\{([A-Za-z_]\w*)\\\}/.freeze
# Variable names are restricted to identifiers, so RFC 6570 operator expressions (e.g. `{?query}`)
# stay literal and never match.
VARIABLE_PATTERN = /\{([A-Za-z_]\w*)\}/.freeze

attr_reader :uri_template_value
attr_reader :title_value
Expand Down Expand Up @@ -38,7 +37,7 @@ def to_h
def inherited(subclass)
super
subclass.instance_variable_set(:@uri_template_value, nil)
subclass.instance_variable_set(:@uri_template_pattern, nil)
subclass.instance_variable_set(:@uri_template_parts, nil)
subclass.instance_variable_set(:@name_value, nil)
subclass.instance_variable_set(:@title_value, nil)
subclass.instance_variable_set(:@description_value, nil)
Expand All @@ -52,7 +51,7 @@ def uri_template(value = NOT_SET)
if value == NOT_SET
@uri_template_value
else
@uri_template_pattern = nil
@uri_template_parts = nil
@uri_template_value = value
end
end
Expand Down Expand Up @@ -120,9 +119,50 @@ def meta(value = NOT_SET)
# Matches a concrete URI against the template's simple RFC 6570 level-1 `{var}` expressions.
# Returns a symbol-keyed Hash of variable values, or `nil` if the URI does not match.
# Variables match one or more characters excluding `/`, and values are not percent-decoded.
#
# The match is the one the pattern `\A` + literals with `(?<var>[^/]+)` for each variable + `\z` finds, each variable
# taking as much as it can from left to right, but it is computed without a backtracking search. Two variables in
# one path segment, as in `{name}.{ext}`, leave that search many ways to split a long run of the separator, and on
# Ruby before 3.2, whose engine does not memoize, a `resources/read` for such a URI kept the whole process busy
# for seconds to minutes. Here a literal that holds a `/` can sit in one place only, since no variable holds one,
# and inside a run of variables between two such places taking the last occurrence of each separator from
# the right gives the same split, so the cost is linear in the length of the URI.
def match_uri(uri)
match = uri_template_pattern&.match(uri)
match&.named_captures&.transform_keys(&:to_sym)
parts = uri_template_parts
# A URI that is not a String, or not valid in its encoding, names no resource; the pattern raised on those.
return unless parts && uri.is_a?(String) && uri.valid_encoding?

literals, names = parts
return unless uri.start_with?(literals.first)

values = []
position = literals.first.length
first = 0

while first < names.size
last = first
last += 1 while last < names.size - 1 && !literals[last + 1].include?("/")

run_end, position_after = variable_run_bounds(uri, position, literals[last + 1])
return unless run_end

last.downto(first + 1) do |index|
separator = literals[index]
latest = run_end - 1 - separator.length
found = latest > position ? uri.rindex(separator, latest) : nil
return unless found && found > position

values[index] = uri[(found + separator.length)...run_end]
run_end = found
end
values[first] = uri[position...run_end]

first = last + 1
position = position_after
end

# A name used twice keeps the value of its last occurrence, as a named group does.
names.zip(values).to_h if position == uri.length
end

def define(uri_template: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, meta: nil, &block)
Expand All @@ -141,12 +181,41 @@ def define(uri_template: nil, name: nil, title: nil, description: nil, icons: []

private

def uri_template_pattern
# The template as `[literals, names]`: the literal texts around the variables, one more than there are variables,
# and the variable names as symbols.
def uri_template_parts
return if uri_template.nil?

@uri_template_pattern ||= begin
pattern = Regexp.escape(uri_template).gsub(VARIABLE_PATTERN) { "(?<#{Regexp.last_match(1)}>[^/]+)" }
Regexp.new("\\A#{pattern}\\z")
@uri_template_parts ||= begin
# Literals and names alternate, starting and ending with a literal; an empty template splits into nothing.
pieces = uri_template.split(VARIABLE_PATTERN, -1)
pieces = [""] if pieces.empty?
pairs = pieces.each_slice(2).to_a

[pairs.map(&:first), pairs.map { |_literal, name| name }.compact.map(&:to_sym)]
end
end

# Where a run of variables that starts at `position` ends, and where the literal closing it ends,
# as `[run_end, position_after]`; `nil` when the closing literal is not there or the run would be empty.
# A closing literal that holds a `/` starts where the first `/` of the rest of the URI puts it, since nothing in
# the run holds one. The literal that closes the last run of a template may hold none, and then it is
# the end of the URI, with no `/` left in the run.
def variable_run_bounds(uri, position, closing)
slash = closing.index("/")
if slash
first_slash = uri.index("/", position)
return unless first_slash

run_end = first_slash - slash
return unless run_end > position && uri[run_end, closing.length] == closing

[run_end, run_end + closing.length]
else
run_end = uri.length - closing.length
return unless run_end > position && uri.end_with?(closing) && !uri[position...run_end].include?("/")

[run_end, uri.length]
end
end
end
Expand Down
70 changes: 70 additions & 0 deletions test/mcp/resource_template_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,76 @@ def contents(user_id:)
assert_nil UserProfileTemplate.match_uri("users://42/extra/profile")
end

test ".match_uri gives each variable of one path segment as much as it can from left to right" do
template_class = Class.new(ResourceTemplate) do
uri_template "file:///{name}.{ext}"
end
adjacent = Class.new(ResourceTemplate) do
uri_template "x://{a}{b}-{c}/end"
end

assert_equal({ name: "archive.tar", ext: "gz" }, template_class.match_uri("file:///archive.tar.gz"))
assert_nil template_class.match_uri("file:///archive")
assert_nil template_class.match_uri("file:///.gz")
assert_equal({ a: "p-q", b: "r", c: "s" }, adjacent.match_uri("x://p-qr-s/end"))
assert_nil adjacent.match_uri("x://p-s/end")
end

test ".match_uri keeps the last value of a variable name used twice" do
template_class = Class.new(ResourceTemplate) do
uri_template "x://{id}/copy/{id}"
end

assert_equal({ id: "2" }, template_class.match_uri("x://1/copy/2"))
end

test ".match_uri agrees with the equivalent pattern on generated templates and URIs" do
# The pattern is what `match_uri` was implemented with; the generated inputs cover literals with and without `/`,
# adjacent variables, repeated names and text that only looks like a variable.
random = Random.new(20261111)
alphabet = ["a", "b", ".", "-", "/", "x", "{", "}"]
literals = ["", "a", ".", "-", "/", "a/", "/a", ".a", "//", "/x/", "{a", "{?q}", "a/b/a"]

2000.times do
template = +literals.sample(random: random)
random.rand(0..4).times { template << "{#{["a", "b", "c"].sample(random: random)}}" << literals.sample(random: random) }
template_class = Class.new(ResourceTemplate) { uri_template template }
groups = Regexp.escape(template).gsub(/\\\{([A-Za-z_]\w*)\\\}/) { "(?<#{Regexp.last_match(1)}>[^/]+)" }
pattern = /\A#{groups}\z/
filled = template.gsub(/\{([A-Za-z_]\w*)\}/) { Array.new(random.rand(1..4)) { alphabet.sample(random: random) }.join }
scrambled = Array.new(random.rand(0..12)) { alphabet.sample(random: random) }.join

[filled, scrambled].each do |uri|
expected = pattern.match(uri)&.named_captures&.transform_keys(&:to_sym)

if expected.nil?
assert_nil(template_class.match_uri(uri), "#{template.inspect} on #{uri.inspect}")
else
assert_equal(expected, template_class.match_uri(uri), "#{template.inspect} on #{uri.inspect}")
end
end
end
end

test ".match_uri answers a long run of separators without a backtracking search" do
# With the pattern, Ruby before 3.2 takes time cubic in the length of this URI: minutes at this size.
template_class = Class.new(ResourceTemplate) do
uri_template "x://{a}-{b}-{c}/end"
end

assert_nil template_class.match_uri("x://#{"-" * 20_000}/")
assert_equal(
{ a: "-" * 19_996, b: "-", c: "-" },
template_class.match_uri("x://#{"-" * 20_000}/end"),
)
end

test ".match_uri returns nil for a URI that is not a String or not valid in its encoding" do
assert_nil UserProfileTemplate.match_uri(42)
assert_nil UserProfileTemplate.match_uri(nil)
assert_nil UserProfileTemplate.match_uri("users://4\xFF/profile".dup.force_encoding(Encoding::UTF_8))
end

test ".match_uri returns nil when uri_template is not set" do
template_class = Class.new(ResourceTemplate)

Expand Down