mcp 1.11.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,10 +5,9 @@ module MCP
5
5
  class << self
6
6
  NOT_SET = Object.new
7
7
 
8
- # Applied after `Regexp.escape`, which turns `{` and `}` into `\{` and `\}`.
9
- # Variable names are restricted to valid Regexp named-group names,
10
- # so RFC 6570 operator expressions (e.g. `{?query}`) stay literal and never match.
11
- VARIABLE_PATTERN = /\\\{([A-Za-z_]\w*)\\\}/.freeze
8
+ # Variable names are restricted to identifiers, so RFC 6570 operator expressions (e.g. `{?query}`)
9
+ # stay literal and never match.
10
+ VARIABLE_PATTERN = /\{([A-Za-z_]\w*)\}/.freeze
12
11
 
13
12
  attr_reader :uri_template_value
14
13
  attr_reader :title_value
@@ -38,7 +37,7 @@ module MCP
38
37
  def inherited(subclass)
39
38
  super
40
39
  subclass.instance_variable_set(:@uri_template_value, nil)
41
- subclass.instance_variable_set(:@uri_template_pattern, nil)
40
+ subclass.instance_variable_set(:@uri_template_parts, nil)
42
41
  subclass.instance_variable_set(:@name_value, nil)
43
42
  subclass.instance_variable_set(:@title_value, nil)
44
43
  subclass.instance_variable_set(:@description_value, nil)
@@ -52,7 +51,7 @@ module MCP
52
51
  if value == NOT_SET
53
52
  @uri_template_value
54
53
  else
55
- @uri_template_pattern = nil
54
+ @uri_template_parts = nil
56
55
  @uri_template_value = value
57
56
  end
58
57
  end
@@ -120,9 +119,50 @@ module MCP
120
119
  # Matches a concrete URI against the template's simple RFC 6570 level-1 `{var}` expressions.
121
120
  # Returns a symbol-keyed Hash of variable values, or `nil` if the URI does not match.
122
121
  # Variables match one or more characters excluding `/`, and values are not percent-decoded.
122
+ #
123
+ # The match is the one the pattern `\A` + literals with `(?<var>[^/]+)` for each variable + `\z` finds, each variable
124
+ # taking as much as it can from left to right, but it is computed without a backtracking search. Two variables in
125
+ # one path segment, as in `{name}.{ext}`, leave that search many ways to split a long run of the separator, and on
126
+ # Ruby before 3.2, whose engine does not memoize, a `resources/read` for such a URI kept the whole process busy
127
+ # for seconds to minutes. Here a literal that holds a `/` can sit in one place only, since no variable holds one,
128
+ # and inside a run of variables between two such places taking the last occurrence of each separator from
129
+ # the right gives the same split, so the cost is linear in the length of the URI.
123
130
  def match_uri(uri)
124
- match = uri_template_pattern&.match(uri)
125
- match&.named_captures&.transform_keys(&:to_sym)
131
+ parts = uri_template_parts
132
+ # A URI that is not a String, or not valid in its encoding, names no resource; the pattern raised on those.
133
+ return unless parts && uri.is_a?(String) && uri.valid_encoding?
134
+
135
+ literals, names = parts
136
+ return unless uri.start_with?(literals.first)
137
+
138
+ values = []
139
+ position = literals.first.length
140
+ first = 0
141
+
142
+ while first < names.size
143
+ last = first
144
+ last += 1 while last < names.size - 1 && !literals[last + 1].include?("/")
145
+
146
+ run_end, position_after = variable_run_bounds(uri, position, literals[last + 1])
147
+ return unless run_end
148
+
149
+ last.downto(first + 1) do |index|
150
+ separator = literals[index]
151
+ latest = run_end - 1 - separator.length
152
+ found = latest > position ? uri.rindex(separator, latest) : nil
153
+ return unless found && found > position
154
+
155
+ values[index] = uri[(found + separator.length)...run_end]
156
+ run_end = found
157
+ end
158
+ values[first] = uri[position...run_end]
159
+
160
+ first = last + 1
161
+ position = position_after
162
+ end
163
+
164
+ # A name used twice keeps the value of its last occurrence, as a named group does.
165
+ names.zip(values).to_h if position == uri.length
126
166
  end
127
167
 
128
168
  def define(uri_template: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, meta: nil, &block)
@@ -141,12 +181,41 @@ module MCP
141
181
 
142
182
  private
143
183
 
144
- def uri_template_pattern
184
+ # The template as `[literals, names]`: the literal texts around the variables, one more than there are variables,
185
+ # and the variable names as symbols.
186
+ def uri_template_parts
145
187
  return if uri_template.nil?
146
188
 
147
- @uri_template_pattern ||= begin
148
- pattern = Regexp.escape(uri_template).gsub(VARIABLE_PATTERN) { "(?<#{Regexp.last_match(1)}>[^/]+)" }
149
- Regexp.new("\\A#{pattern}\\z")
189
+ @uri_template_parts ||= begin
190
+ # Literals and names alternate, starting and ending with a literal; an empty template splits into nothing.
191
+ pieces = uri_template.split(VARIABLE_PATTERN, -1)
192
+ pieces = [""] if pieces.empty?
193
+ pairs = pieces.each_slice(2).to_a
194
+
195
+ [pairs.map(&:first), pairs.map { |_literal, name| name }.compact.map(&:to_sym)]
196
+ end
197
+ end
198
+
199
+ # Where a run of variables that starts at `position` ends, and where the literal closing it ends,
200
+ # as `[run_end, position_after]`; `nil` when the closing literal is not there or the run would be empty.
201
+ # A closing literal that holds a `/` starts where the first `/` of the rest of the URI puts it, since nothing in
202
+ # the run holds one. The literal that closes the last run of a template may hold none, and then it is
203
+ # the end of the URI, with no `/` left in the run.
204
+ def variable_run_bounds(uri, position, closing)
205
+ slash = closing.index("/")
206
+ if slash
207
+ first_slash = uri.index("/", position)
208
+ return unless first_slash
209
+
210
+ run_end = first_slash - slash
211
+ return unless run_end > position && uri[run_end, closing.length] == closing
212
+
213
+ [run_end, run_end + closing.length]
214
+ else
215
+ run_end = uri.length - closing.length
216
+ return unless run_end > position && uri.end_with?(closing) && !uri[position...run_end].include?("/")
217
+
218
+ [run_end, uri.length]
150
219
  end
151
220
  end
152
221
  end
@@ -1,5 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../client_capabilities"
3
4
  require_relative "../methods"
4
5
  require_relative "../result_type"
5
6
 
@@ -116,9 +117,9 @@ module MCP
116
117
  # (symbol/string tolerant on the declared side).
117
118
  def missing_subtree(required, declared)
118
119
  required.each_with_object({}) do |(name, nested), missing|
119
- declared_value = read_key(declared, name)
120
+ declared_value = ClientCapabilities.value(declared, name)
120
121
 
121
- if declared_value.nil?
122
+ if !declared_value
122
123
  missing[name] = nested
123
124
  elsif nested.is_a?(Hash) && !nested.empty?
124
125
  nested_missing = missing_subtree(nested, declared_value)
@@ -134,21 +135,12 @@ module MCP
134
135
  elicitation_missing = missing[:elicitation]
135
136
  return missing unless elicitation_missing.is_a?(Hash) && elicitation_missing.key?(:form)
136
137
 
137
- declared_elicitation = read_key(declared, :elicitation)
138
- return missing unless declared_elicitation.is_a?(Hash)
139
- return missing unless read_key(declared_elicitation, :url).nil?
138
+ return missing unless ClientCapabilities.elicitation?(declared, :form)
140
139
 
141
140
  pruned = elicitation_missing.reject { |key, _| key == :form }
142
141
  pruned.empty? ? missing.reject { |key, _| key == :elicitation } : missing.merge(elicitation: pruned)
143
142
  end
144
143
 
145
- def read_key(hash, key)
146
- return unless hash.is_a?(Hash)
147
-
148
- value = hash[key.to_sym]
149
- value.nil? ? hash[key.to_s] : value
150
- end
151
-
152
144
  def deep_merge(left, right)
153
145
  left.merge(right) do |_key, left_value, right_value|
154
146
  if left_value.is_a?(Hash) && right_value.is_a?(Hash)
@@ -87,6 +87,12 @@ module MCP
87
87
  access_token
88
88
  end
89
89
 
90
+ # The default `inspect` would print the `client_secret` this verifier authenticates to the introspection endpoint with.
91
+ def inspect
92
+ "#<#{self.class.name} introspection_endpoint=#{@introspection_endpoint.inspect} client_id=#{@client_id.inspect} " \
93
+ "client_secret=#{@client_secret.nil? ? "nil" : "[present]"} client_auth_method=#{@client_auth_method.inspect}>"
94
+ end
95
+
90
96
  private
91
97
 
92
98
  def introspect(token)
@@ -118,6 +118,12 @@ module MCP
118
118
  raise InvalidTokenError, "Invalid token"
119
119
  end
120
120
 
121
+ # The default `inspect` would print the `key:`, which for HMAC algorithms is the shared secret itself.
122
+ def inspect
123
+ "#<#{self.class.name} issuer=#{@issuer.inspect} audience=#{@audience.inspect} jwks_uri=#{@jwks_uri.inspect} " \
124
+ "key=#{@key.nil? ? "nil" : "[present]"} algorithms=#{@algorithms.inspect}>"
125
+ end
126
+
121
127
  private
122
128
 
123
129
  def decode(token)
@@ -38,8 +38,8 @@ module MCP
38
38
  unless key.is_a?(String) && key.bytesize == KEY_BYTES
39
39
  raise ArgumentError, "key must be a #{KEY_BYTES}-byte String"
40
40
  end
41
- unless ttl.is_a?(Numeric) && ttl.positive?
42
- raise ArgumentError, "ttl must be a positive number of seconds"
41
+ unless ttl.is_a?(Numeric) && ttl.finite? && ttl.positive?
42
+ raise ArgumentError, "ttl must be a positive, finite number of seconds"
43
43
  end
44
44
 
45
45
  @key = key.dup.force_encoding(Encoding::BINARY).freeze
@@ -47,11 +47,17 @@ module MCP
47
47
  @audience = audience
48
48
  end
49
49
 
50
+ # The default `inspect` would print the `key:`, with which anyone can seal a state this server accepts.
51
+ def inspect
52
+ "#<#{self.class.name} ttl=#{@ttl.inspect} audience=#{@audience.inspect}>"
53
+ end
54
+
50
55
  # Seals a plaintext state into an opaque token bound to the originating request.
51
56
  def seal(state, method:, target:, arguments_digest:)
52
57
  claims = {
53
58
  v: 1,
54
- exp: Time.now.to_i + @ttl,
59
+ # Whole seconds, as `verify!` requires: an `Integer` TTL keeps its exact value, a fractional one ends within the second it falls in.
60
+ exp: (Time.now + @ttl).to_i,
55
61
  m: method,
56
62
  t: target,
57
63
  a: arguments_digest,
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../subscriptions"
4
+
5
+ module MCP
6
+ class Server
7
+ # The change-event seam between notification publishers and open `subscriptions/listen` streams (SEP-2575).
8
+ # `StreamableHTTPTransport` publishes a typed event for every tools/prompts/resources change and
9
+ # delivers events arriving via `subscribe` to the matching streams it holds. This default bus is in-process:
10
+ # `publish` invokes the registered listeners synchronously, so a single-process deployment behaves exactly as if
11
+ # the transport wrote to its streams directly.
12
+ #
13
+ # In a multi-process deployment (such as Puma clustered mode), each worker holds only its own listen streams,
14
+ # so a change published in one worker must reach the streams the other workers hold. Pass a bus backed by an external
15
+ # pub/sub system (Redis, Postgres NOTIFY, and the like) via `StreamableHTTPTransport.new(server, subscription_bus: ...)`.
16
+ # A custom bus implements the same two methods:
17
+ #
18
+ # - `publish(event)` delivers the event to the listeners registered in every process, including the publishing one.
19
+ # - `subscribe { |event| ... }` registers a listener called once per arriving event and returns a callable that unregisters it.
20
+ #
21
+ # The bus carries the typed events of `MCP::Subscriptions` (`ToolsListChanged`, `PromptsListChanged`,
22
+ # `ResourcesListChanged`, and `ResourceUpdated`), never JSON-RPC: subscription-id stamping and per-stream filter
23
+ # matching stay in the transport, so a bus implementation can only move events between processes.
24
+ # Listeners are synchronous and must not raise; the wire encoding an external backend uses between processes
25
+ # is the implementation's own. The unregistering callable is idempotent (the transport calls it on `close`).
26
+ # Listeners run outside the bus's own locks, on whichever thread receives the event, and one already selected for
27
+ # delivery may still run after unregistering; the transport tolerates that through each stream's closed check.
28
+ # `publish` runs on the notifier's thread, so a broker round trip belongs behind a timeout; a `publish` that raises
29
+ # is reported by the transport without failing the notifier.
30
+ class SubscriptionBus
31
+ def initialize
32
+ @mutex = Mutex.new
33
+ @listeners = {}
34
+ end
35
+
36
+ # Delivers the event synchronously to every registered listener. A raising listener is
37
+ # reported through the configured exception reporter and does not stop delivery to the
38
+ # remaining listeners.
39
+ def publish(event)
40
+ listeners = @mutex.synchronize { @listeners.values }
41
+ listeners.each do |listener|
42
+ listener.call(event)
43
+ rescue => e
44
+ MCP.configuration.exception_reporter.call(e, { error: "SubscriptionBus listener failed" })
45
+ end
46
+ nil
47
+ end
48
+
49
+ # Registers a listener for published events and returns a callable that unregisters it.
50
+ def subscribe(&listener)
51
+ raise ArgumentError, "subscribe requires a block" unless listener
52
+
53
+ token = Object.new
54
+ @mutex.synchronize { @listeners[token] = listener }
55
+
56
+ proc do
57
+ @mutex.synchronize { @listeners.delete(token) }
58
+ nil
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
@@ -155,9 +155,11 @@ module MCP
155
155
  raise
156
156
  end
157
157
 
158
- if parsed[:id] == request_id && !parsed.key?(:method)
159
- if parsed[:error]
160
- raise StandardError, "Client returned an error for #{method} request (code: #{parsed[:error][:code]}): #{parsed[:error][:message]}"
158
+ # A frame that is not an object is not the response; it is answered like any other frame, as `open` does.
159
+ if parsed.is_a?(Hash) && parsed[:id] == request_id && !parsed.key?(:method)
160
+ if parsed.key?(:error)
161
+ error = parsed[:error].is_a?(Hash) ? parsed[:error] : {}
162
+ raise StandardError, "Client returned an error for #{method} request (code: #{error[:code]}): #{error[:message]}"
161
163
  end
162
164
 
163
165
  return parsed[:result]