mcp 1.9.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: 95dcc461ef4ba74c3128e82441b81587135488d8c9e4d17f5ea91ba45867f080
4
- data.tar.gz: 2d0afc689585aad6ffaf37c4ca5528497e30bf81e733514a05faf724cfb3e2f4
3
+ metadata.gz: a7387e5c2a8bc058687718d9e1d2a9e876c914adf72ca9ffa3105091afe2bcbb
4
+ data.tar.gz: 4a3f2b69ffec38ef5141df63b63505219bbd06180a49316306d36d8b6254358f
5
5
  SHA512:
6
- metadata.gz: 68e755e7b252d6680ca82ce073b3e541e0b4202ac18ce5b73a5175c326aa655e7cbdf4d0685cdb06d4007cc35696b0e7ad60c7a50820567b63b84e4cce5d7c7c
7
- data.tar.gz: 68a614ac492dfcfa34a1429efc57e031089dfa65b10db2f6b18b9d0bbffe6ebbcb03c13eacbac9cb3dea178fda603b279825b2cb67ccb81081523db809e27e98
6
+ metadata.gz: c1be8465ddd4a52f68ec4a69f548846aaca2df9c47c5b930af0ec65c5c489de9f04415f2c6e9b99a94ebdf22c4dee534e1f867988d18407a6a531b5881dff89c
7
+ data.tar.gz: be116455c8537480257a1ac835bb4974561f750b4a110e26cc4d11d661cdb5ab42b6ebb9eee9e448aed998832a1abc248c200273558f24bf9a58ac52b371fc29
data/README.md CHANGED
@@ -122,6 +122,9 @@ response = client.call_tool(
122
122
  stdio_transport.close
123
123
  ```
124
124
 
125
+ Stdio servers inherit only a small base environment by default, including `GEM_HOME` and `GEM_PATH`.
126
+ Pass extra variables through `env:`, or set `inherit_env: true` to restore full inheritance.
127
+
125
128
  The same client can connect to Streamable HTTP servers with `MCP::Client::HTTP`;
126
129
  see [Client Transports](https://ruby.sdk.modelcontextprotocol.io/client/transports/).
127
130
 
@@ -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?
@@ -227,7 +239,7 @@ module JsonRpcHandler
227
239
  end
228
240
 
229
241
  def valid_method_name?(method)
230
- method.is_a?(String) && !method.start_with?("rpc.")
242
+ method.is_a?(String) && method.valid_encoding? && !method.start_with?("rpc.")
231
243
  end
232
244
 
233
245
  def valid_params?(params)
@@ -6,7 +6,7 @@ require_relative "../configuration"
6
6
  require_relative "../methods"
7
7
  require_relative "../protocol_deprecations"
8
8
  require_relative "../version"
9
- require_relative "mcp_param_headers"
9
+ require_relative "../mcp_param_headers"
10
10
  require_relative "modern_envelope"
11
11
 
12
12
  module MCP
@@ -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
@@ -545,8 +546,12 @@ module MCP
545
546
  def send_notification(notification:)
546
547
  method = notification[:method] || notification["method"]
547
548
 
548
- redacting_authorization_header { client.post("", notification, session_headers) }
549
+ redacting_authorization_header do
550
+ client.post("", notification, session_headers) { |req| req.options.on_data = bounded_on_data }
551
+ end
549
552
  nil
553
+ rescue MessageTooLargeError => e
554
+ raise RequestHandlerError.new(e.message, { method: method }, error_type: :internal_error)
550
555
  rescue Faraday::Error => e
551
556
  raise RequestHandlerError.new(
552
557
  "Failed to send #{method} notification",
@@ -573,7 +578,11 @@ module MCP
573
578
  end
574
579
 
575
580
  begin
576
- redacting_authorization_header { client.delete("", nil, session_headers) }
581
+ redacting_authorization_header do
582
+ client.delete("", nil, session_headers) { |req| req.options.on_data = bounded_on_data }
583
+ end
584
+ rescue MessageTooLargeError => e
585
+ raise RequestHandlerError.new(e.message, {}, error_type: :internal_error)
577
586
  rescue Faraday::ClientError => e
578
587
  raise unless [404, 405].include?(e.response&.dig(:status))
579
588
  ensure
@@ -1196,12 +1205,13 @@ module MCP
1196
1205
  error: { code: e.code, message: e.message },
1197
1206
  }
1198
1207
  rescue StandardError => e
1208
+ warn("MCP::Client::HTTP: error handling #{message["method"]} request: #{e.class}: #{e.message.dump}")
1199
1209
  {
1200
1210
  jsonrpc: JsonRpcHandler::Version::V2_0,
1201
1211
  id: message["id"],
1202
1212
  error: {
1203
1213
  code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR,
1204
- message: "Internal error handling #{message["method"]} request: #{e.message}",
1214
+ message: "Internal error",
1205
1215
  },
1206
1216
  }
1207
1217
  end
@@ -1233,7 +1243,22 @@ module MCP
1233
1243
  end
1234
1244
 
1235
1245
  def send_client_response(response)
1236
- redacting_authorization_header { client.post("", response, session_headers) }
1246
+ redacting_authorization_header do
1247
+ client.post("", response, session_headers) { |req| req.options.on_data = bounded_on_data }
1248
+ end
1249
+ end
1250
+
1251
+ # Counts discarded response bytes without parsing the body, whatever its content type.
1252
+ def bounded_on_data
1253
+ received_bytes = 0
1254
+
1255
+ proc do |chunk, _received_bytes, _env|
1256
+ received_bytes += chunk.bytesize
1257
+
1258
+ if received_bytes > @max_message_bytes
1259
+ raise MessageTooLargeError, "Server response body exceeds #{@max_message_bytes} bytes"
1260
+ end
1261
+ end
1237
1262
  end
1238
1263
 
1239
1264
  def parse_json_buffer(buffer, method, params)
@@ -35,6 +35,10 @@ 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,
39
+ # as its metadata states it: an `https` URL, or `http` on a loopback address, without query or fragment.
40
+ # A different authorization server raises `Flow::AuthorizationError`. Omitting this is deprecated
41
+ # and emits a warning; without it, credentials go to whichever authorization server the MCP server names.
38
42
  # - `scope` - String of space-separated scopes to request when the server's
39
43
  # `WWW-Authenticate` and the Protected Resource Metadata do not specify one.
40
44
  # - `storage` - Object responding to `tokens`, `save_tokens(tokens)`, `client_information`,
@@ -59,12 +63,14 @@ module MCP
59
63
 
60
64
  attr_reader :scope, :storage
61
65
 
66
+ # @note Omitting `issuer:` is deprecated. Pass the authorization server's issuer URL to limit the credentials to that server.
62
67
  def initialize(
63
68
  client_id:,
64
69
  client_secret: nil,
65
70
  token_endpoint_auth_method: "client_secret_basic",
66
71
  private_key: nil,
67
72
  signing_algorithm: nil,
73
+ issuer: nil,
68
74
  scope: nil,
69
75
  storage: nil,
70
76
  authorization_request_validator: nil,
@@ -82,7 +88,19 @@ module MCP
82
88
  "client_credentials request is not allowed."
83
89
  end
84
90
 
91
+ if issuer.nil?
92
+ warn(
93
+ "Omitting `issuer:` is deprecated. Without it, the credentials go to whichever authorization server " \
94
+ "the MCP server names. Pass the authorization server's issuer URL as `issuer:` so they are only sent there.",
95
+ uplevel: 1,
96
+ )
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}."
100
+ end
101
+
85
102
  client_information = { "client_id" => client_id, "token_endpoint_auth_method" => token_endpoint_auth_method }
103
+ client_information["issuer"] = issuer if issuer
86
104
 
87
105
  if token_endpoint_auth_method == "private_key_jwt"
88
106
  validate_private_key_jwt_arguments!(
@@ -21,6 +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
+ # 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.
24
28
  # - `scope` - String of space-separated scopes to request when the server's `WWW-Authenticate` and
25
29
  # the Protected Resource Metadata do not specify one.
26
30
  # - `storage` - Object responding to `tokens`, `save_tokens(tokens)`, `client_information`, and `save_client_information(info)`.
@@ -41,10 +45,12 @@ module MCP
41
45
 
42
46
  attr_reader :scope, :storage
43
47
 
48
+ # @note Omitting `issuer:` is deprecated. Pass the authorization server's issuer URL to limit the credentials to that server.
44
49
  def initialize(
45
50
  client_id:,
46
51
  client_secret:,
47
52
  assertion_provider:,
53
+ issuer: nil,
48
54
  scope: nil,
49
55
  storage: nil,
50
56
  authorization_request_validator: nil,
@@ -63,6 +69,17 @@ module MCP
63
69
  raise InvalidConfigurationError, "assertion_provider must be callable as `call(audience:, resource:)` and return the ID-JAG assertion."
64
70
  end
65
71
 
72
+ if issuer.nil?
73
+ warn(
74
+ "Omitting `issuer:` is deprecated. Without it, the credentials go to whichever authorization server " \
75
+ "the MCP server names. Pass the authorization server's issuer URL as `issuer:` so they are only sent there.",
76
+ uplevel: 1,
77
+ )
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}."
81
+ end
82
+
66
83
  http_client_customizer = validated_http_client_customizer(http_client_customizer)
67
84
 
68
85
  @assertion_provider = assertion_provider
@@ -71,11 +88,13 @@ module MCP
71
88
  @authorization_request_validator = authorization_request_validator
72
89
  @token_request_params = frozen_token_request_params(token_request_params)
73
90
  @http_client_customizer = http_client_customizer
74
- @storage.save_client_information(
91
+ client_information = {
75
92
  "client_id" => client_id,
76
93
  "client_secret" => client_secret,
77
94
  "token_endpoint_auth_method" => "client_secret_basic",
78
- )
95
+ }
96
+ client_information["issuer"] = issuer if issuer
97
+ @storage.save_client_information(client_information)
79
98
  end
80
99
 
81
100
  # See `Provider#authorization_flow`.
@@ -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.
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "base64"
4
3
  require "json"
5
4
  require "openssl"
6
5
  require "securerandom"
@@ -380,7 +379,8 @@ module MCP
380
379
  def ensure_client_credentials_issuer!(client_info, as_metadata:)
381
380
  stored_issuer = client_info_required_value(client_info, "issuer")
382
381
  return if stored_issuer.nil?
383
- return if stored_issuer == as_metadata["issuer"]
382
+
383
+ return if issuers_match?(stored_issuer, as_metadata["issuer"])
384
384
 
385
385
  raise AuthorizationError,
386
386
  "Stored client credentials are bound to a different authorization server " \
@@ -399,6 +399,7 @@ module MCP
399
399
  unless client_info.is_a?(Hash) && client_info_required_value(client_info, "client_id")
400
400
  raise AuthorizationError, "Cannot run the jwt-bearer grant: the provider has no stored `client_id`."
401
401
  end
402
+ ensure_client_credentials_issuer!(client_info, as_metadata: as_metadata)
402
403
 
403
404
  # Asked before the assertion is minted, for the same reason registration waits on the authorization-code grant:
404
405
  # obtaining an ID-JAG sends the identity provider an audience of this authorization server, which must not happen once
@@ -630,7 +631,7 @@ module MCP
630
631
  end
631
632
 
632
633
  if prm
633
- authorization_server = first_authorization_server(prm)
634
+ authorization_server = advertised_authorization_server(prm)
634
635
  ensure_secure_url!(authorization_server, label: "PRM `authorization_servers` entry")
635
636
  ensure_routable_destination!(
636
637
  authorization_server,
@@ -719,31 +720,50 @@ module MCP
719
720
  ensure_issuer_matches!(expected: expected, returned: returned)
720
721
  end
721
722
 
722
- # Reads `authorization_servers` from a PRM document and returns
723
- # the first entry, raising `AuthorizationError` for any of the malformed
724
- # shapes a non-compliant server could emit (missing field, non-Array
725
- # value, empty Array, non-String first entry). Centralizing this lets
726
- # both the full flow and the refresh flow share the same defensive
727
- # parse instead of each one duplicating a Hash-and-Array check.
728
- 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)
729
733
  authorization_servers = prm["authorization_servers"]
730
734
  unless authorization_servers.is_a?(Array)
731
- raise AuthorizationError,
732
- "Protected resource metadata `authorization_servers` is not an array " \
733
- "(got #{authorization_servers.class})."
735
+ raise AuthorizationError, "Protected resource metadata `authorization_servers` is not an array (got #{authorization_servers.class})."
734
736
  end
735
737
 
736
738
  if authorization_servers.empty?
737
739
  raise AuthorizationError, "Protected resource metadata has no authorization_servers."
738
740
  end
739
741
 
740
- first = authorization_servers.first
741
- 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?
742
747
  raise AuthorizationError,
743
748
  "Protected resource metadata `authorization_servers[0]` is not a non-empty string."
744
749
  end
745
750
 
746
- 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
747
767
  end
748
768
 
749
769
  # Walks candidate metadata URLs and returns the parsed body of the first 2xx response that is a JSON object;
@@ -1106,6 +1126,11 @@ module MCP
1106
1126
  end
1107
1127
 
1108
1128
  def ensure_refreshable_client_information!(client_info, as_metadata:)
1129
+ case provider_authorization_flow
1130
+ when :client_credentials, :jwt_bearer
1131
+ return ensure_client_credentials_issuer!(client_info, as_metadata: as_metadata)
1132
+ end
1133
+
1109
1134
  stored_issuer = client_info_required_value(client_info, "issuer")
1110
1135
  return if stored_issuer.nil?
1111
1136
  return if stored_issuer == as_metadata["issuer"]
@@ -1644,7 +1669,7 @@ module MCP
1644
1669
  def basic_auth_credentials(client_id, client_secret)
1645
1670
  encoded_id = URI.encode_www_form_component(client_id)
1646
1671
  encoded_secret = URI.encode_www_form_component(client_secret)
1647
- Base64.strict_encode64("#{encoded_id}:#{encoded_secret}")
1672
+ ["#{encoded_id}:#{encoded_secret}"].pack("m0")
1648
1673
  end
1649
1674
 
1650
1675
  def http_get(url)
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "base64"
4
3
  require "json"
5
4
  require "openssl"
6
5
  require "securerandom"
@@ -118,8 +117,10 @@ module MCP
118
117
  end.join.then { |hex| [hex].pack("H*") }
119
118
  end
120
119
 
120
+ # base64url without padding (RFC 7515 Section 2), spelled with `pack` because `base64` is no longer
121
+ # a default gem as of Ruby 3.4 and this gem does not depend on it.
121
122
  def base64url(data)
122
- Base64.urlsafe_encode64(data, padding: false)
123
+ [data].pack("m0").tr("+/", "-_").delete("=")
123
124
  end
124
125
  end
125
126
  end
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "base64"
4
3
  require "digest"
5
4
  require "securerandom"
6
5
 
@@ -27,7 +26,9 @@ module MCP
27
26
  # Generates a PKCE pair (code_verifier and S256 code_challenge).
28
27
  def generate
29
28
  verifier = SecureRandom.urlsafe_base64(64)
30
- challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
29
+ # base64url without padding (RFC 7636 Appendix A), spelled with `pack` because `base64` is no longer
30
+ # a default gem as of Ruby 3.4 and this gem does not depend on it.
31
+ challenge = [Digest::SHA256.digest(verifier)].pack("m0").tr("+/", "-_").delete("=")
31
32
 
32
33
  { code_verifier: verifier, code_challenge: challenge, code_challenge_method: "S256" }
33
34
  end
@@ -34,9 +34,20 @@ module MCP
34
34
  # Matches the C# SDK's `DiscoverProbeTimeout` default.
35
35
  DEFAULT_DISCOVER_PROBE_TIMEOUT = 5
36
36
 
37
+ # Inherited Windows environment, including RubyGems paths.
38
+ WINDOWS_INHERITED_ENV_VARS = %w[
39
+ APPDATA HOMEDRIVE HOMEPATH LOCALAPPDATA PATH PATHEXT PROCESSOR_ARCHITECTURE
40
+ SYSTEMDRIVE SYSTEMROOT TEMP USERNAME USERPROFILE GEM_HOME GEM_PATH
41
+ ].freeze
42
+
43
+ # Inherited Unix environment, including RubyGems paths.
44
+ UNIX_INHERITED_ENV_VARS = %w[HOME LOGNAME PATH SHELL TERM USER GEM_HOME GEM_PATH].freeze
45
+
46
+ DEFAULT_INHERITED_ENV_VARS = Gem.win_platform? ? WINDOWS_INHERITED_ENV_VARS : UNIX_INHERITED_ENV_VARS
47
+
37
48
  attr_reader :command, :args, :env, :server_info
38
49
 
39
- def initialize(command:, args: [], env: nil, read_timeout: nil, max_line_bytes: MAX_LINE_BYTES)
50
+ def initialize(command:, args: [], env: nil, inherit_env: false, read_timeout: nil, max_line_bytes: MAX_LINE_BYTES)
40
51
  # Reject `nil` or non-positive values: `IO#gets("\n", nil)` and a negative
41
52
  # limit read without an upper bound, which would silently disable the
42
53
  # protection this option exists to provide.
@@ -47,6 +58,7 @@ module MCP
47
58
  @command = command
48
59
  @args = args
49
60
  @env = env
61
+ @inherit_env = inherit_env
50
62
  @read_timeout = read_timeout
51
63
  @max_line_bytes = max_line_bytes
52
64
  @stdin = nil
@@ -166,8 +178,8 @@ module MCP
166
178
  def start
167
179
  raise "MCP::Client::Stdio already started" if @started
168
180
 
169
- spawn_env = @env || {}
170
- @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(spawn_env, @command, *@args)
181
+ spawn_env = DEFAULT_INHERITED_ENV_VARS.to_h { |key| [key, ENV[key]] }.compact.merge(@env || {})
182
+ @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(spawn_env, @command, *@args, unsetenv_others: !@inherit_env)
171
183
  @stdout.set_encoding("UTF-8")
172
184
  @stdin.set_encoding("UTF-8")
173
185
 
@@ -484,10 +496,13 @@ module MCP
484
496
  parsed["method"] == MCP::Methods::PING && json_rpc_id?(parsed["id"]) && JsonRpcHandler.valid_version?(parsed["jsonrpc"])
485
497
  end
486
498
 
487
- # An id the pong could not write back is skipped too: a String that is not valid UTF-8, or a number
488
- # 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.
489
502
  def json_rpc_id?(id)
490
- (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?)
491
506
  end
492
507
 
493
508
  def ensure_running!
data/lib/mcp/client.rb CHANGED
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "client/elicitation"
4
- require_relative "client/mcp_param_headers"
5
4
  require_relative "client/modern_envelope"
6
5
  require_relative "client/oauth"
7
6
  require_relative "client/stdio"
@@ -20,6 +19,11 @@ module MCP
20
19
  # every response would otherwise be followed indefinitely, growing the retained pages with it.
21
20
  MAX_PAGES = 1_000
22
21
 
22
+ # The custom-header codec lived under this name until the server transport came to share it;
23
+ # the name stays for code that referenced it.
24
+ # @api private
25
+ McpParamHeaders = MCP::McpParamHeaders
26
+
23
27
  class ServerError < StandardError
24
28
  attr_reader :code, :data
25
29
 
@@ -5,16 +5,17 @@ module MCP
5
5
  def instrument_call(method, server_context: {}, exception_already_reported: nil, &block)
6
6
  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
7
7
  begin
8
- @instrumentation_data = {}
9
- add_instrumentation_data(method: method)
8
+ instrumentation_data = {}
9
+ @instrumentation_data = instrumentation_data
10
+ instrumentation_data.merge!(method: method)
10
11
  # `self.` is required: the `server_context:` keyword above shadows the
11
12
  # reader, and the value we want here is the user-defined hash passed to
12
13
  # `Server.new`, not the per-call reporter context.
13
14
  if configuration.instrument_server_context? && respond_to?(:server_context)
14
- add_instrumentation_data(server_context: self.server_context)
15
+ instrumentation_data.merge!(server_context: self.server_context)
15
16
  end
16
17
 
17
- result = configuration.around_request.call(@instrumentation_data, &block)
18
+ result = configuration.around_request.call(instrumentation_data) { block.call(instrumentation_data) }
18
19
 
19
20
  result
20
21
  rescue => e
@@ -28,22 +29,26 @@ module MCP
28
29
  end
29
30
 
30
31
  unless already_reported
31
- add_instrumentation_data(error: :internal_error) unless @instrumentation_data.key?(:error)
32
+ instrumentation_data.merge!(error: :internal_error) unless instrumentation_data.key?(:error)
32
33
  configuration.exception_reporter.call(e, server_context)
33
34
  end
34
35
 
35
36
  raise
36
37
  ensure
37
38
  end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
38
- add_instrumentation_data(duration: end_time - start_time)
39
+ instrumentation_data.merge!(duration: end_time - start_time)
39
40
 
40
41
  # Backward compatibility: `instrumentation_callback` is soft-deprecated
41
42
  # in favor of `around_request`, but existing callers still expect it
42
43
  # to fire after every request until it is removed in a future version.
43
- configuration.instrumentation_callback.call(@instrumentation_data)
44
+ configuration.instrumentation_callback.call(instrumentation_data)
44
45
  end
45
46
  end
46
47
 
48
+ # @deprecated Use the data hash passed to the {#instrument_call} block or
49
+ # `around_request` instead. `add_instrumentation_data` uses a shared record
50
+ # and is not safe for concurrent calls.
51
+ # @see #instrument_call
47
52
  def add_instrumentation_data(**kwargs)
48
53
  @instrumentation_data.merge!(kwargs)
49
54
  end