mcp 1.10.0 → 1.11.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 87d807c4e295950341aa7123459ac862a601c3bb840a881ac2a8c48ae2b8b2f0
4
- data.tar.gz: b09a469593f943812b51f7d1f3db3eb1fb6d1c63c4d321c1cf6d6936158f842a
3
+ metadata.gz: a7387e5c2a8bc058687718d9e1d2a9e876c914adf72ca9ffa3105091afe2bcbb
4
+ data.tar.gz: 4a3f2b69ffec38ef5141df63b63505219bbd06180a49316306d36d8b6254358f
5
5
  SHA512:
6
- metadata.gz: 124b4d117e0b4c0079a4af053d2de713bce66847f1c0d95404cd99d54a929ef0f250669b7207c8d6658ced4a70e63f1708376dcbe379a848f65cf8e4c5880cc0
7
- data.tar.gz: 4e77573617cbafc37ac1b1fb59aee3fe6f96825c474fc912ca24f766c6690fd3d5df4b2e0c24831210b4d8c7700340f1daf4043ceaa3977b8dfaf589b5e75a01
6
+ metadata.gz: c1be8465ddd4a52f68ec4a69f548846aaca2df9c47c5b930af0ec65c5c489de9f04415f2c6e9b99a94ebdf22c4dee534e1f867988d18407a6a531b5881dff89c
7
+ data.tar.gz: be116455c8537480257a1ac835bb4974561f750b4a110e26cc4d11d661cdb5ab42b6ebb9eee9e448aed998832a1abc248c200273558f24bf9a58ac52b371fc29
@@ -130,6 +130,8 @@ module JsonRpcHandler
130
130
  # and a notification carries no id member at all. Refused rather than run as a notification,
131
131
  # since a sender that wrote an id meant to be answered.
132
132
  "Request ID must not be null"
133
+ elsif oversized_integer_id?(id)
134
+ "Request ID must be an integer of at most #{MAX_INTEGER_ID_BITS} bits"
133
135
  elsif !valid_id?(id, id_validation_pattern)
134
136
  if id_validation_pattern
135
137
  "Request ID must be a string matching the validation pattern, or an integer"
@@ -217,8 +219,18 @@ module JsonRpcHandler
217
219
  version == Version::V2_0
218
220
  end
219
221
 
222
+ # An integer id is written back into the response, and writing an integer out in decimal takes time that grows
223
+ # faster than its length: one of a few million digits, which fits in a request body, costs a minute of CPU.
224
+ # 128 bits leaves room for any counter and for a UUID carried as a number.
225
+ MAX_INTEGER_ID_BITS = 128
226
+
227
+ def oversized_integer_id?(id)
228
+ id.is_a?(Integer) && id.bit_length > MAX_INTEGER_ID_BITS
229
+ end
230
+
220
231
  def valid_id?(id, pattern = nil)
221
- return true if id.nil? || id.is_a?(Integer)
232
+ return true if id.nil?
233
+ return !oversized_integer_id?(id) if id.is_a?(Integer)
222
234
  # A string that is not valid in its encoding cannot be written into the response,
223
235
  # and matching a pattern against it raises, so it is refused before the method runs.
224
236
  return false unless id.is_a?(String) && id.valid_encoding?
@@ -217,8 +217,9 @@ module MCP
217
217
  elsif parsed["method"] && parsed.key?("id") && JsonRpcHandler.valid_version?(parsed["jsonrpc"])
218
218
  # A server-to-client request (e.g. `elicitation/create`) delivered on the stream while
219
219
  # the original request is still pending. One that is not JSON-RPC 2.0 is dropped unanswered,
220
- # as the TypeScript client drops it at schema validation.
221
- @on_request&.call(parsed)
220
+ # as the TypeScript client drops it at schema validation, and so is one whose integer id is
221
+ # too large to write back at a reasonable cost.
222
+ @on_request&.call(parsed) unless JsonRpcHandler.oversized_integer_id?(parsed["id"])
222
223
  end
223
224
  end
224
225
  end
@@ -35,7 +35,8 @@ module MCP
35
35
  # the server's `token_endpoint_auth_signing_alg_values_supported` fails
36
36
  # loudly at construction instead of as a 401 (the TypeScript and Python SDKs
37
37
  # also take the algorithm as an explicit option).
38
- # - `issuer` - String issuer identifier of the authorization server the credentials belong to.
38
+ # - `issuer` - String issuer identifier of the authorization server the credentials belong to,
39
+ # as its metadata states it: an `https` URL, or `http` on a loopback address, without query or fragment.
39
40
  # A different authorization server raises `Flow::AuthorizationError`. Omitting this is deprecated
40
41
  # and emits a warning; without it, credentials go to whichever authorization server the MCP server names.
41
42
  # - `scope` - String of space-separated scopes to request when the server's
@@ -93,8 +94,9 @@ module MCP
93
94
  "the MCP server names. Pass the authorization server's issuer URL as `issuer:` so they are only sent there.",
94
95
  uplevel: 1,
95
96
  )
96
- elsif !issuer.is_a?(String) || blank?(issuer)
97
- raise InvalidCredentialsError, "issuer must be a non-empty String: the issuer identifier of the authorization server the credentials belong to."
97
+ elsif !Discovery.issuer_identifier?(issuer)
98
+ raise InvalidCredentialsError, "issuer must be the authorization server's issuer URL as its metadata states it, over HTTPS " \
99
+ "(HTTP only on a loopback address) and without query or fragment, got #{issuer.inspect}."
98
100
  end
99
101
 
100
102
  client_information = { "client_id" => client_id, "token_endpoint_auth_method" => token_endpoint_auth_method }
@@ -21,9 +21,10 @@ module MCP
21
21
  #
22
22
  # Optional keyword arguments:
23
23
  #
24
- # - `issuer` - String issuer identifier of the MCP authorization server the credentials belong to.
25
- # A mismatch raises `Flow::AuthorizationError` before `assertion_provider` is called. Omitting this is
26
- # deprecated and emits a warning; without it, credentials go to whichever authorization server the MCP server names.
24
+ # - `issuer` - String issuer identifier of the MCP authorization server the credentials belong to,
25
+ # as its metadata states it: an `https` URL, or `http` on a loopback address, without query or fragment.
26
+ # A mismatch raises `Flow::AuthorizationError` before `assertion_provider` is called. Omitting this is deprecated
27
+ # and emits a warning; without it, credentials go to whichever authorization server the MCP server names.
27
28
  # - `scope` - String of space-separated scopes to request when the server's `WWW-Authenticate` and
28
29
  # the Protected Resource Metadata do not specify one.
29
30
  # - `storage` - Object responding to `tokens`, `save_tokens(tokens)`, `client_information`, and `save_client_information(info)`.
@@ -74,8 +75,9 @@ module MCP
74
75
  "the MCP server names. Pass the authorization server's issuer URL as `issuer:` so they are only sent there.",
75
76
  uplevel: 1,
76
77
  )
77
- elsif !issuer.is_a?(String) || blank?(issuer)
78
- raise InvalidConfigurationError, "issuer must be a non-empty String: the issuer identifier of the authorization server the credentials belong to."
78
+ elsif !Discovery.issuer_identifier?(issuer)
79
+ raise InvalidConfigurationError, "issuer must be the authorization server's issuer URL as its metadata states it, over HTTPS " \
80
+ "(HTTP only on a loopback address) and without query or fragment, got #{issuer.inspect}."
79
81
  end
80
82
 
81
83
  http_client_customizer = validated_http_client_customizer(http_client_customizer)
@@ -200,6 +200,20 @@ module MCP
200
200
  false
201
201
  end
202
202
 
203
+ # Whether `value` can be an authorization server issuer identifier the flow could ever match: a String naming an `https` URL,
204
+ # or `http` on a loopback address as `secure_url?` allows, without query or fragment (RFC 8414 Section 2).
205
+ # The issuer of the metadata is compared as a String, so a value of another type would never equal it, and an issuer with
206
+ # a query or fragment is one no authorization server may publish.
207
+ def issuer_identifier?(value)
208
+ return false unless value.is_a?(String) && secure_url?(value)
209
+
210
+ uri = URI.parse(value)
211
+
212
+ uri.query.nil? && uri.fragment.nil?
213
+ rescue URI::InvalidURIError
214
+ false
215
+ end
216
+
203
217
  # Returns true when `url` and `other` share an origin: same scheme, same host,
204
218
  # and same port. Scheme and host compare case-insensitively, and an implicit default port compares
205
219
  # equal to the same port written out, because `URI::HTTP#port` already resolves to the default.
@@ -380,9 +380,7 @@ module MCP
380
380
  stored_issuer = client_info_required_value(client_info, "issuer")
381
381
  return if stored_issuer.nil?
382
382
 
383
- current_issuer = as_metadata["issuer"]
384
- return if stored_issuer == current_issuer
385
- return if stored_issuer == "#{current_issuer}/" || "#{stored_issuer}/" == current_issuer
383
+ return if issuers_match?(stored_issuer, as_metadata["issuer"])
386
384
 
387
385
  raise AuthorizationError,
388
386
  "Stored client credentials are bound to a different authorization server " \
@@ -633,7 +631,7 @@ module MCP
633
631
  end
634
632
 
635
633
  if prm
636
- authorization_server = first_authorization_server(prm)
634
+ authorization_server = advertised_authorization_server(prm)
637
635
  ensure_secure_url!(authorization_server, label: "PRM `authorization_servers` entry")
638
636
  ensure_routable_destination!(
639
637
  authorization_server,
@@ -722,31 +720,50 @@ module MCP
722
720
  ensure_issuer_matches!(expected: expected, returned: returned)
723
721
  end
724
722
 
725
- # Reads `authorization_servers` from a PRM document and returns
726
- # the first entry, raising `AuthorizationError` for any of the malformed
727
- # shapes a non-compliant server could emit (missing field, non-Array
728
- # value, empty Array, non-String first entry). Centralizing this lets
729
- # both the full flow and the refresh flow share the same defensive
730
- # parse instead of each one duplicating a Hash-and-Array check.
731
- def first_authorization_server(prm)
723
+ # Reads `authorization_servers` from a PRM document and returns the entry to use, raising `AuthorizationError` for any of
724
+ # the malformed shapes a non-compliant server could emit (missing field, non-Array value, empty Array, non-String entry).
725
+ # Centralizing this lets both the full flow and the refresh flow share the same defensive parse instead of each one duplicating
726
+ # a Hash-and-Array check.
727
+ #
728
+ # When the provider's stored client information records an `issuer` (the `issuer:` of a machine-to-machine provider,
729
+ # or the authorization server that issued a registration), the entry naming that issuer is preferred over the first one,
730
+ # as the Python SDK does: a protected resource may list several authorization servers, and the client's credentials are
731
+ # usable at only one of them. Without a match the first entry is used as before, and the issuer checks that follow decide.
732
+ def advertised_authorization_server(prm)
732
733
  authorization_servers = prm["authorization_servers"]
733
734
  unless authorization_servers.is_a?(Array)
734
- raise AuthorizationError,
735
- "Protected resource metadata `authorization_servers` is not an array " \
736
- "(got #{authorization_servers.class})."
735
+ raise AuthorizationError, "Protected resource metadata `authorization_servers` is not an array (got #{authorization_servers.class})."
737
736
  end
738
737
 
739
738
  if authorization_servers.empty?
740
739
  raise AuthorizationError, "Protected resource metadata has no authorization_servers."
741
740
  end
742
741
 
743
- first = authorization_servers.first
744
- unless first.is_a?(String) && !first.empty?
742
+ stored_issuer = stored_client_information_issuer
743
+ chosen = authorization_servers.find { |entry| entry.is_a?(String) && issuers_match?(entry, stored_issuer) } if stored_issuer
744
+ chosen ||= authorization_servers.first
745
+
746
+ unless chosen.is_a?(String) && !chosen.empty?
745
747
  raise AuthorizationError,
746
748
  "Protected resource metadata `authorization_servers[0]` is not a non-empty string."
747
749
  end
748
750
 
749
- first
751
+ chosen
752
+ end
753
+
754
+ # The `issuer` recorded in the provider's stored client information, or `nil`.
755
+ def stored_client_information_issuer
756
+ info = @provider.client_information
757
+ return unless info.is_a?(Hash)
758
+
759
+ client_info_required_value(info, "issuer")
760
+ end
761
+
762
+ # Whether two issuer identifiers name the same authorization server: identical, or differing by one trailing slash,
763
+ # as the TypeScript SDK's `issuersMatch` accepts (an issuer derived from a URL is often rendered with the slash
764
+ # the metadata leaves out). Any other difference keeps them distinct.
765
+ def issuers_match?(first, second)
766
+ first == second || first == "#{second}/" || "#{first}/" == second
750
767
  end
751
768
 
752
769
  # Walks candidate metadata URLs and returns the parsed body of the first 2xx response that is a JSON object;
@@ -496,10 +496,13 @@ module MCP
496
496
  parsed["method"] == MCP::Methods::PING && json_rpc_id?(parsed["id"]) && JsonRpcHandler.valid_version?(parsed["jsonrpc"])
497
497
  end
498
498
 
499
- # An id the pong could not write back is skipped too: a String that is not valid UTF-8, or a number
500
- # such as `1e400`, which the parser reads as an infinite Float that JSON cannot represent.
499
+ # An id the pong could not write back is skipped too: a String that is not valid UTF-8,
500
+ # a number such as `1e400`, which the parser reads as an infinite Float that JSON cannot represent,
501
+ # or an integer too large to write back at a reasonable cost.
501
502
  def json_rpc_id?(id)
502
- (id.is_a?(String) && id.valid_encoding?) || id.is_a?(Integer) || (id.is_a?(Float) && id.finite?)
503
+ return !JsonRpcHandler.oversized_integer_id?(id) if id.is_a?(Integer)
504
+
505
+ (id.is_a?(String) && id.valid_encoding?) || (id.is_a?(Float) && id.finite?)
503
506
  end
504
507
 
505
508
  def ensure_running!
@@ -168,8 +168,8 @@ module MCP
168
168
  # instead of failing the token. The unverified payload is inspected first: a claim that is neither a finite number
169
169
  # nor a digit string makes the token invalid, the same answer `expiry_from_claims` gives an introspection response.
170
170
  def validate_time_claims!(token)
171
- payload, = JWT.decode(token, nil, false)
172
- raise InvalidTokenError, "Invalid token" unless payload.is_a?(Hash)
171
+ payload, header = unverified_segments(token)
172
+ raise InvalidTokenError, "Invalid token" unless payload.is_a?(Hash) && header.is_a?(Hash)
173
173
 
174
174
  NUMERIC_DATE_CLAIMS.each do |name|
175
175
  value = payload[name]
@@ -179,6 +179,16 @@ module MCP
179
179
  end
180
180
  end
181
181
 
182
+ # The gem reads members of the JOSE header before it has checked that the header is an object, so a header that is
183
+ # an array, a number or a boolean raises an error that is not a `JWT::DecodeError`, here or in the verifying decode
184
+ # depending on the gem version. Such a token is invalid like any other malformed one, not a failure of this server,
185
+ # so `validate_time_claims!` refuses it before the verifying decode sees it.
186
+ def unverified_segments(token)
187
+ JWT.decode(token, nil, false)
188
+ rescue TypeError, NoMethodError
189
+ raise InvalidTokenError, "Invalid token"
190
+ end
191
+
182
192
  # `none` is never acceptable, and HMAC must not share an allowlist with asymmetric algorithms: an attacker who picks `alg`
183
193
  # would otherwise sign with the public key bytes as the HMAC secret. A String key can only be an HMAC secret,
184
194
  # so it is refused for asymmetric algorithms at construction rather than failing every verification later, and a `JWT::JWK`
@@ -33,6 +33,10 @@ module MCP
33
33
  VALIDATED_MEMBERS = ["resource", "authorization_servers", "scopes_supported", "resource_name", "resource_documentation", "bearer_methods_supported"].freeze
34
34
  private_constant :VALIDATED_MEMBERS
35
35
 
36
+ # One or more host name labels in front of `localhost`.
37
+ LOCALHOST_SUBDOMAIN = /\A(?:[a-z0-9-]+\.)+localhost\z/.freeze
38
+ private_constant :LOCALHOST_SUBDOMAIN
39
+
36
40
  attr_reader :resource, :authorization_servers, :scopes_supported, :resource_name, :resource_documentation, :bearer_methods_supported, :extra
37
41
 
38
42
  def initialize(resource:, authorization_servers:, scopes_supported: nil, resource_name: nil, resource_documentation: nil, bearer_methods_supported: DEFAULT_BEARER_METHODS_SUPPORTED, extra: {})
@@ -43,9 +47,9 @@ module MCP
43
47
  raise ArgumentError, "authorization_servers must contain at least one issuer URL" if servers.empty?
44
48
 
45
49
  servers.each do |server|
46
- next if Client::OAuth::Discovery.secure_url?(server)
50
+ next if secure_identifier?(server)
47
51
 
48
- raise ArgumentError, "authorization_servers must use https (http is allowed only on loopback): #{server.inspect}"
52
+ raise ArgumentError, "authorization_servers must use https (http is allowed only on loopback or a name under localhost): #{server.inspect}"
49
53
  end
50
54
 
51
55
  overridden = extra.keys.map(&:to_s) & VALIDATED_MEMBERS
@@ -126,12 +130,34 @@ module MCP
126
130
  raise ArgumentError, "resource must not contain a fragment per RFC 8707: #{resource.inspect}"
127
131
  end
128
132
 
129
- unless Client::OAuth::Discovery.secure_url?(resource.to_s)
130
- raise ArgumentError, "resource must use https (http is allowed only on loopback): #{resource.inspect}"
133
+ unless secure_identifier?(resource.to_s)
134
+ raise ArgumentError, "resource must use https (http is allowed only on loopback or a name under localhost): #{resource.inspect}"
131
135
  end
132
136
 
133
137
  uri
134
138
  end
139
+
140
+ # Whether `url` may stand in this document: what `Discovery.secure_url?` admits, and plain `http` on a name under
141
+ # `localhost` (`http://acme.localhost:3000/mcp`), the way a server that gives each tenant a subdomain is run in development.
142
+ #
143
+ # The wider rule is for these two members only, because this server never connects to them: `resource` is published
144
+ # and compared with a token's audience, `authorization_servers` is published and compared with its issuer.
145
+ # Such a name is reserved for loopback and cannot be registered (RFC 6761 Section 6.3),
146
+ # but a resolver is not bound to answer it with the loopback address, which is why `secure_url?`, the check for
147
+ # a URL that is connected to (`jwks_uri:`, `introspection_endpoint:`, everything in the client), keeps to `localhost` itself.
148
+ # The host is read from the parsed URL, so `x.localhost.example.com` and `x.localhost@example.com` are ordinary names,
149
+ # and it has to be made of host name labels: `URI` leaves a percent-encoded host as written,
150
+ # and `example.com%2F.localhost` would otherwise end the right way.
151
+ def secure_identifier?(url)
152
+ return true if Client::OAuth::Discovery.secure_url?(url)
153
+
154
+ uri = URI.parse(url.to_s)
155
+ return false unless uri.scheme&.downcase == "http"
156
+
157
+ uri.host.to_s.downcase.delete_suffix(".").match?(LOCALHOST_SUBDOMAIN)
158
+ rescue URI::InvalidURIError
159
+ false
160
+ end
135
161
  end
136
162
  end
137
163
  end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MCP
4
+ class Server
5
+ module Transports
6
+ # The contract of the store `StreamableHTTPTransport` keeps SSE events in for resumability (MCP 2025-11-25,
7
+ # SEP-1699): the transport stores each event it writes under the id the store assigns, and a client that
8
+ # reconnects with `Last-Event-ID` is sent the events of that stream stored after the one it names.
9
+ #
10
+ # A store serves every session of the transport. Stream ids are opaque strings the transport mints,
11
+ # one for the GET stream of a session and one for the response stream of each request; a store orders
12
+ # the events of one stream by storage order and never has to relate streams to each other.
13
+ # The SDK ships this contract and no store of its own. `examples/in_memory_event_store.rb` in its repository
14
+ # is one that keeps events in the process, to copy into an application; a deployment whose reconnects may reach
15
+ # another process implements this interface against a shared backend.
16
+ class EventStore
17
+ # Stores `message`, the JSON text of a JSON-RPC message, on the stream `stream_id` and returns the id
18
+ # assigned to it, a String without line breaks that is unique across the store. `message` is `nil` for
19
+ # the priming event that opens a stream, which is stored so that its id is a cursor like any other,
20
+ # but is never replayed.
21
+ def store_event(stream_id, message)
22
+ raise NotImplementedError, "#{self.class} must implement #store_event"
23
+ end
24
+
25
+ # The events stored on the same stream after the event `last_event_id`, as `[stream_id, events]`
26
+ # where `events` is an Array of `[event_id, message]` pairs in storage order, priming events left out;
27
+ # `nil` when the store does not know `last_event_id`, which includes an event it has since dropped.
28
+ def events_after(last_event_id)
29
+ raise NotImplementedError, "#{self.class} must implement #events_after"
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -91,7 +91,7 @@ module MCP
91
91
  def internal_error_response(parsed)
92
92
  response = { jsonrpc: JsonRpcHandler::Version::V2_0 }
93
93
  id = parsed[:id] if parsed.is_a?(Hash)
94
- response[:id] = id if id.is_a?(Integer) || (id.is_a?(String) && id.valid_encoding?)
94
+ response[:id] = id if !id.nil? && JsonRpcHandler.valid_id?(id)
95
95
  response[:error] = { code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR, message: "Internal error" }
96
96
  response
97
97
  end