mcp 1.5.1 → 1.6.1

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.
@@ -14,7 +14,38 @@ module MCP
14
14
  # `Provider`; this class consumes a Provider plus signal data extracted from
15
15
  # the failing response (resource_metadata URL, scope challenge).
16
16
  class Flow
17
- class AuthorizationError < StandardError; end
17
+ TOKEN_ENDPOINT_ERROR_MAX_LENGTH = 128
18
+ TOKEN_ENDPOINT_ERROR_DESCRIPTION_MAX_LENGTH = 512
19
+ METADATA_DIAGNOSTIC_MAX_LENGTH = 128
20
+ METADATA_URL_MAX_LENGTH = 2048
21
+
22
+ # Token request parameters the flow sets itself. Its values win over a provider's `token_request_params`,
23
+ # so a provider naming one of these is refused rather than left believing its value was sent.
24
+ RESERVED_TOKEN_REQUEST_PARAMS = [
25
+ "grant_type",
26
+ "client_id",
27
+ "client_secret",
28
+ "client_assertion",
29
+ "client_assertion_type",
30
+ "scope",
31
+ "resource",
32
+ "code",
33
+ "code_verifier",
34
+ "redirect_uri",
35
+ "refresh_token",
36
+ "assertion",
37
+ ].freeze
38
+
39
+ class AuthorizationError < StandardError
40
+ attr_reader :http_status, :error, :error_description
41
+
42
+ def initialize(message = nil, http_status: nil, error: nil, error_description: nil)
43
+ super(message)
44
+ @http_status = http_status
45
+ @error = error
46
+ @error_description = error_description
47
+ end
48
+ end
18
49
 
19
50
  # Raised specifically when the token endpoint rejects a grant with
20
51
  # `error: "invalid_grant"` (RFC 6749 §5.2). Callers use this to
@@ -28,6 +59,136 @@ module MCP
28
59
  # or authorization server metadata failure by rescuing a class rather than by matching the message text.
29
60
  class AuthorizationRefusedError < AuthorizationError; end
30
61
 
62
+ # Raised by metadata discovery when every candidate URL answered that nothing usable is published there
63
+ # (a `4xx` other than `429`, a redirect that was not followed, or a body that is not a JSON object).
64
+ # The only discovery failure that may select the legacy 2025-03-26 path.
65
+ class MetadataNotPublishedError < AuthorizationError; end
66
+
67
+ # Raised by metadata discovery when the answer says nothing about what is published: the request failed to
68
+ # reach the server, or a candidate answered `5xx` or `429`. Falling back on this would move
69
+ # the flow to a different authorization server because of a transient failure, so it is surfaced instead,
70
+ # as the TypeScript SDK does for network errors outside browsers and the Python SDK does for both.
71
+ class MetadataUnreachableError < AuthorizationError; end
72
+
73
+ # Raised for a `token_request_params` value the SDK refuses: a reserved key, a Hash comparing keys by identity,
74
+ # or anything but a Hash of Strings. An `ArgumentError` because the value is a configuration mistake,
75
+ # not a failed authorization, and deliberately outside `AuthorizationError`, which `MCP::Client::HTTP` treats on
76
+ # a failed refresh as a reason to run the interactive flow.
77
+ class InvalidTokenRequestParamsError < ArgumentError; end
78
+
79
+ # Raised by `RequestedOriginGuard` when middleware added through the provider's `http_client_customizer`
80
+ # would send a request to an origin other than the one the flow validated, or has dropped the record of
81
+ # the URL the flow asked for. An `ArgumentError` because the middleware is a configuration mistake,
82
+ # and deliberately outside `AuthorizationError`, which discovery treats as "nothing published"
83
+ # and `MCP::Client::HTTP` treats on a failed refresh as a reason to run the interactive flow.
84
+ class DestinationMismatchError < ArgumentError; end
85
+
86
+ # Faraday middleware registered on the connection `build_http_client` assembles before the customizer
87
+ # is invoked, so with the usual `use` it sits ahead of the customizer's middleware and sees the URL exactly
88
+ # as the flow requested it, which it records on the request environment for `RequestedOriginGuard`.
89
+ # The guard covers what happens to a request after that record; middleware inserted ahead of it with
90
+ # `builder.insert(0, ...)` that rewrites the URL before it or rebuilds the environment is outside the guard.
91
+ # The record lives on the environment, not in `env.request.context`: that slot belongs to the application,
92
+ # which may fill it on the connection or replace it from a middleware of its own. Only the first URL seen
93
+ # on an environment is recorded: a middleware inserted ahead of this one that re-enters the stack after
94
+ # a `3xx` with the same environment, or with its `dup`, which shares the record, cannot replace it with
95
+ # the redirected URL.
96
+ class RequestedURLStamp
97
+ KEY = :mcp_oauth_requested_url
98
+
99
+ def initialize(app)
100
+ @app = app
101
+ end
102
+
103
+ def call(env)
104
+ env[KEY] ||= env.url.to_s
105
+ @app.call(env)
106
+ end
107
+ end
108
+
109
+ # Faraday middleware registered last on that connection, so it sees `env.url` after any customizer-added
110
+ # middleware has rewritten it or followed a redirect. A request that would leave the origin the flow asked
111
+ # for is refused before it reaches the adapter, since every destination check ran against the URL as
112
+ # written; a same-origin change stays with the server those checks admitted. The record survives
113
+ # the `env.dup` that redirect-following middleware performs, and a request that arrives without it is
114
+ # refused as well, so a middleware that rebuilds the environment fails closed rather than open.
115
+ # The origin boundary resembles the one the Python SDK keeps for its own auth requests, which follows
116
+ # a redirect itself only within the origin; this flow follows none.
117
+ class RequestedOriginGuard
118
+ def initialize(app)
119
+ @app = app
120
+ end
121
+
122
+ def call(env)
123
+ requested = env[RequestedURLStamp::KEY]
124
+ unless requested
125
+ raise DestinationMismatchError, <<~MESSAGE
126
+ Request to #{Discovery.canonicalize_origin_and_path(env.url.to_s).inspect} carries no record of \
127
+ the URL the flow asked for; middleware that rebuilds the request environment is refused.
128
+ MESSAGE
129
+ end
130
+
131
+ unless Discovery.same_origin?(env.url.to_s, requested)
132
+ raise DestinationMismatchError, <<~MESSAGE
133
+ Request to #{Discovery.canonicalize_origin_and_path(requested).inspect} would be sent to \
134
+ #{Discovery.canonicalize_origin_and_path(env.url.to_s).inspect}, on a different origin; \
135
+ middleware that follows redirects or rewrites URLs is refused.
136
+ MESSAGE
137
+ end
138
+
139
+ @app.call(env)
140
+ end
141
+ end
142
+ private_constant :RequestedURLStamp, :RequestedOriginGuard
143
+
144
+ class << self
145
+ # Returns why `params` cannot ride a token request as `token_request_params`, or `nil` when it can.
146
+ # Shared by the provider constructors and the flow, which both refuse the value with `InvalidTokenRequestParamsError`,
147
+ # so the same problem reads the same wherever it surfaces.
148
+ def token_request_params_problem(params)
149
+ return "must be a Hash (got #{params.class})." unless params.is_a?(Hash)
150
+
151
+ # Two equal keys are two entries here, which would be sent twice from a provider method
152
+ # or silently collapse into one when the constructors copy the Hash.
153
+ return "must not compare keys by identity." if params.compare_by_identity?
154
+
155
+ params.each do |key, value|
156
+ return "keys must be Strings (got #{key.class})." unless key.is_a?(String)
157
+ return "values must be Strings (got #{value.class} for #{key.inspect})." unless value.is_a?(String)
158
+ return "must not set #{key.inspect}, which the SDK sets itself." if RESERVED_TOKEN_REQUEST_PARAMS.include?(key)
159
+ end
160
+
161
+ nil
162
+ end
163
+
164
+ # Builds the connection the flow uses for its own requests: the SDK's defaults, `RequestedURLStamp`,
165
+ # then `customizer` (a provider's `http_client_customizer`, called with the `Faraday::Connection`),
166
+ # then `RequestedOriginGuard` last so it sees what the customizer's middleware does to each request
167
+ # after the stamp recorded it. Every request on the connection passes through both, so a caller using
168
+ # it directly is held to the same origin rule.
169
+ #
170
+ # Deliberately built without redirect-following middleware. Every destination check in this class runs
171
+ # against the URL as written, before the request goes out, so a connection that transparently followed
172
+ # a `3xx` would let a server reach a host the checks just refused. The guard turns following at
173
+ # the middleware level into a refusal; following inside an adapter stays invisible, so a customizer must
174
+ # not enable it.
175
+ #
176
+ # `Accept-Encoding` is deliberately left unset. `Net::HTTP::GenericRequest` negotiates it and decodes
177
+ # the response only while the caller has not claimed that header; assigning it turns `decode_content` off,
178
+ # which would silently move `BoundedBody`'s cap onto compressed bytes and let a small body expand past it
179
+ # after the check.
180
+ def build_http_client(customizer = nil)
181
+ require "faraday"
182
+
183
+ Faraday.new do |faraday|
184
+ faraday.headers["Accept"] = "application/json"
185
+ faraday.use(RequestedURLStamp)
186
+ customizer&.call(faraday)
187
+ faraday.use(RequestedOriginGuard)
188
+ end
189
+ end
190
+ end
191
+
31
192
  def initialize(provider:, http_client_factory: nil)
32
193
  @provider = provider
33
194
  @http_client_factory = http_client_factory || -> { default_http_client }
@@ -75,7 +236,7 @@ module MCP
75
236
 
76
237
  ensure_pkce_supported!(as_metadata)
77
238
 
78
- effective_scope = resolve_scope(scope: scope, prm: prm || {})
239
+ effective_scope = resolve_scope(scope: scope, prm: prm)
79
240
  effective_scope = normalize_offline_access_scope(effective_scope, as_metadata: as_metadata)
80
241
 
81
242
  # Asked before registering, not after: a refusal must not leave this client registered at an authorization server
@@ -126,7 +287,7 @@ module MCP
126
287
  # Runs the OAuth 2.1 `client_credentials` grant (machine-to-machine, no user interaction) and persists
127
288
  # the resulting token. Shares the same discovery and security checks as `run!`; the only difference is
128
289
  # the grant exchanged at the token endpoint. There is no PKCE, redirect, or authorization request,
129
- # and no `offline_access` augmentation because the grant does not issue a refresh token (OAuth 2.1 Section 4.3.3).
290
+ # and no `offline_access` augmentation because the grant is not expected to issue a refresh token (OAuth 2.1 Section 4.3.3).
130
291
  # The pre-registered `client_id` / `client_secret` come from the provider's stored `client_information`.
131
292
  # https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization
132
293
  def run_client_credentials!(as_metadata:, prm:, resource:, scope:, server_url:)
@@ -219,19 +380,22 @@ module MCP
219
380
  # checks before talking to it.
220
381
  #
221
382
  # Returns `:refreshed` on success. Raises `AuthorizationError` when the provider has no refresh token, no client information,
383
+ # when a `client_credentials` or `jwt-bearer` provider's tokens record no issuer,
222
384
  # or when the token endpoint refuses the refresh request.
223
385
  # https://www.rfc-editor.org/rfc/rfc6749#section-6
224
386
  def refresh!(server_url:, resource_metadata_url: nil)
225
387
  refresh_token = read_token("refresh_token")
226
388
  raise AuthorizationError, "Cannot refresh: no refresh_token in provider storage." unless refresh_token
227
389
 
390
+ ensure_refresh_token_issuer_recorded!
391
+
228
392
  stored_client_info = @provider.client_information
229
393
  have_stored_client_info = stored_client_info.is_a?(Hash) && client_info_required_value(stored_client_info, "client_id")
230
394
 
231
395
  # A CIMD-configured provider stores no `client_information` on purpose
232
396
  # (the CIMD URL is re-resolved against the live AS metadata on every flow).
233
397
  # Allow refresh to proceed in that case so the `refresh_token` obtained via the CIMD flow remains usable.
234
- have_cimd_url = !@provider.client_id_metadata_document_url.nil?
398
+ have_cimd_url = !provider_client_id_metadata_document_url.nil?
235
399
 
236
400
  unless have_stored_client_info || have_cimd_url
237
401
  raise AuthorizationError, "Cannot refresh: no client_information in provider storage."
@@ -267,7 +431,7 @@ module MCP
267
431
  ensure_refreshable_client_information!(stored_client_info, as_metadata: as_metadata)
268
432
  stored_client_info
269
433
  elsif as_metadata["client_id_metadata_document_supported"] == true
270
- { "client_id" => @provider.client_id_metadata_document_url }
434
+ { "client_id" => provider_client_id_metadata_document_url }
271
435
  else
272
436
  raise AuthorizationError,
273
437
  "Cannot refresh: provider has a CIMD URL but the authorization server no longer advertises " \
@@ -319,7 +483,12 @@ module MCP
319
483
  #
320
484
  # Legacy path (2025-03-26 backwards compatibility): when the server publishes no PRM, `prm` is nil
321
485
  # and the MCP server's own origin acts as the authorization base URL, matching the TypeScript and Python SDKs.
322
- # Any PRM discovery failure (404s, network errors, malformed documents) selects the legacy path, mirroring both SDKs' behavior.
486
+ # Only a discovery answer saying that nothing usable is published (`MetadataNotPublishedError`: a `4xx` other than `429`,
487
+ # a redirect that was not followed, or a body that is not a JSON object) selects the legacy path.
488
+ # A request that failed to reach the server, or returned a `5xx` or `429`, says nothing about what the server publishes,
489
+ # so once no candidate has served a usable document it is surfaced instead (`MetadataUnreachableError`),
490
+ # as both SDKs do for network errors (the TypeScript SDK outside browsers) and the Python SDK does for server errors.
491
+ # A body over the response cap is refused outright and never reaches the fallback either.
323
492
  # https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization#fallbacks-for-servers-without-metadata-discovery
324
493
  def locate_authorization_server(server_url:, resource_metadata_url:)
325
494
  prm = begin
@@ -327,7 +496,7 @@ module MCP
327
496
  server_url: server_url,
328
497
  resource_metadata_url: resource_metadata_url,
329
498
  )
330
- rescue AuthorizationError
499
+ rescue MetadataNotPublishedError
331
500
  nil
332
501
  end
333
502
 
@@ -349,16 +518,26 @@ module MCP
349
518
 
350
519
  # Fetches and validates the authorization server's RFC 8414 metadata.
351
520
  #
352
- # On the modern path the metadata `issuer` must be byte-identical to the discovery URL (RFC 8414 Section 3.3).
353
- # On the legacy 2025-03-26 path that validation is skipped: the legacy spec predates the requirement,
354
- # and a pre-PRM server may host its OAuth endpoints under a path prefix whose `issuer` legitimately differs from
355
- # the origin the metadata was discovered at (neither the TypeScript nor the Python SDK validates the issuer on this path).
521
+ # The metadata `issuer` must be byte-identical to the discovery URL (RFC 8414 Section 3.3) on both paths.
522
+ # On the legacy 2025-03-26 path the discovery URL is the MCP server's origin, which that spec names as
523
+ # the authorization base URL and which a document may render with a trailing slash; the TypeScript and Python SDKs
524
+ # accept the same slash-only difference. A document naming any other issuer is refused: an unverified `issuer`
525
+ # would otherwise become the identity tokens and client information are bound to, assertions are minted for,
526
+ # and the validator is shown, so a server could claim another authorization server and unlock the credentials
527
+ # bound to it.
356
528
  # When even the metadata document is absent, the legacy spec's default endpoints are used.
357
529
  def authorization_server_metadata(authorization_server:, legacy:, server_url:)
358
530
  metadata = if legacy
359
- begin
531
+ fetched = begin
360
532
  fetch_authorization_server_metadata(issuer_url: authorization_server)
361
533
  rescue AuthorizationError
534
+ nil
535
+ end
536
+
537
+ if fetched
538
+ ensure_legacy_issuer_matches!(expected: authorization_server, returned: fetched["issuer"])
539
+ fetched
540
+ else
362
541
  default_legacy_metadata(authorization_server)
363
542
  end
364
543
  else
@@ -403,6 +582,14 @@ module MCP
403
582
  fetch_metadata_json(urls, label: "authorization server metadata")
404
583
  end
405
584
 
585
+ # The legacy authorization base is an origin, which a document may render as `https://host/`;
586
+ # both name the same server, and nothing else does.
587
+ def ensure_legacy_issuer_matches!(expected:, returned:)
588
+ return if returned == "#{expected}/"
589
+
590
+ ensure_issuer_matches!(expected: expected, returned: returned)
591
+ end
592
+
406
593
  # Reads `authorization_servers` from a PRM document and returns
407
594
  # the first entry, raising `AuthorizationError` for any of the malformed
408
595
  # shapes a non-compliant server could emit (missing field, non-Array
@@ -430,44 +617,63 @@ module MCP
430
617
  first
431
618
  end
432
619
 
433
- # Walks candidate metadata URLs and returns the parsed JSON body of
434
- # the first 2xx response. Raises `AuthorizationError` for transport
435
- # failures (`Faraday::Error`) and malformed bodies (`JSON::ParserError`)
436
- # so callers do not have to handle raw Faraday/JSON exceptions.
620
+ # Walks candidate metadata URLs and returns the parsed body of the first 2xx response that is a JSON object;
621
+ # the caller checks its fields. Candidates are tried until one serves such a body, since a later one may still
622
+ # be usable when an earlier one is broken or down (the URL from `WWW-Authenticate` against the well-known path,
623
+ # or the OAuth document against the OpenID one). Once the candidates are exhausted, an answer that said nothing
624
+ # about what is published (a network error, a `5xx`, or a `429`) outranks the rest and raises
625
+ # `MetadataUnreachableError`; otherwise (any other status, such as a `4xx` other than `429` or a redirect that
626
+ # was not followed, a body that is not JSON, or not a JSON object) `MetadataNotPublishedError`.
627
+ # A body over the cap is refused outright by `bounded_request` with a plain `AuthorizationError`,
628
+ # before any classification. Each failure is listed with its URL stripped of userinfo, query and fragment
629
+ # and cut to `METADATA_URL_MAX_LENGTH`, but otherwise spelled as requested, so it can be matched against
630
+ # a server's access log, and with exception text bounded, since the message lands in every log destination
631
+ # the error passes through.
437
632
  def fetch_metadata_json(urls, label:)
438
- last_error = nil
633
+ failures = []
634
+ inconclusive = false
439
635
  urls.each do |url|
440
636
  response = begin
441
637
  http_get(url)
442
638
  rescue Faraday::Error => e
443
- last_error = "GET #{url} raised #{e.class}: #{e.message}"
639
+ detail = bounded_diagnostic(e.message, limit: METADATA_DIAGNOSTIC_MAX_LENGTH)
640
+ failures << "GET #{reported_url(url)} raised #{[e.class, detail].compact.join(": ")}"
641
+ inconclusive = true
444
642
  next
445
643
  end
446
644
 
447
- if response.status >= 200 && response.status < 300
448
- parsed = begin
449
- JSON.parse(response_body_string(response))
450
- rescue JSON::ParserError => e
451
- raise AuthorizationError, "Failed to parse #{label} from #{url}: #{e.message}."
452
- end
645
+ unless response.status >= 200 && response.status < 300
646
+ failures << "GET #{reported_url(url)} returned #{response.status}"
647
+ inconclusive = true if response.status >= 500 || response.status == 429
648
+ next
649
+ end
453
650
 
454
- # Even valid JSON can be the wrong shape (a top-level array,
455
- # a bare `null`, a string, ...). The discovery callers index by
456
- # name (`prm["authorization_servers"]`, etc.), so anything that
457
- # is not a Hash would raise `TypeError` / `NoMethodError`
458
- # downstream. Surface that as `AuthorizationError` instead so
459
- # callers see a single, documented error type.
460
- unless parsed.is_a?(Hash)
461
- raise AuthorizationError,
462
- "#{label} from #{url} is not a JSON object (got #{parsed.class})."
463
- end
651
+ parsed = begin
652
+ JSON.parse(response_body_string(response))
653
+ rescue JSON::ParserError => e
654
+ detail = bounded_diagnostic(e.message, limit: METADATA_DIAGNOSTIC_MAX_LENGTH) || e.class.name
655
+ failures << "GET #{reported_url(url)} returned a body that is not JSON: #{detail}"
656
+ next
657
+ end
464
658
 
465
- return parsed
659
+ # Even valid JSON can be the wrong shape (a top-level array, a bare `null`, a string, ...).
660
+ # The discovery callers index by name (`prm["authorization_servers"]`, etc.), so anything that
661
+ # is not a Hash would raise `TypeError` / `NoMethodError` downstream.
662
+ unless parsed.is_a?(Hash)
663
+ failures << "GET #{reported_url(url)} returned a body that is not a JSON object (got #{parsed.class})"
664
+ next
466
665
  end
467
666
 
468
- last_error = "GET #{url} returned #{response.status}"
667
+ return parsed
668
+ end
669
+
670
+ message = "Failed to fetch #{label}: #{failures.join("; ")}."
671
+
672
+ if inconclusive
673
+ raise MetadataUnreachableError, message
674
+ else
675
+ raise MetadataNotPublishedError, message
469
676
  end
470
- raise AuthorizationError, "Failed to fetch #{label}: #{last_error}."
471
677
  end
472
678
 
473
679
  def ensure_pkce_supported!(as_metadata)
@@ -628,7 +834,7 @@ module MCP
628
834
  # (or the operator may rotate the CIMD URL), and a stale `client_information` entry would otherwise
629
835
  # keep sending the old CIMD URL forever. Re-evaluating on every flow re-reads the current AS metadata
630
836
  # and the current `provider.client_id_metadata_document_url`.
631
- cimd_url = @provider.client_id_metadata_document_url
837
+ cimd_url = provider_client_id_metadata_document_url
632
838
  if cimd_url && as_metadata["client_id_metadata_document_supported"] == true
633
839
  return { "client_id" => cimd_url }
634
840
  end
@@ -758,6 +964,18 @@ module MCP
758
964
  MESSAGE
759
965
  end
760
966
 
967
+ # `Provider` tolerates tokens stored before the issuer was recorded (see `ensure_token_issuer!`).
968
+ # The `client_credentials` and `jwt-bearer` providers have no such tokens, since their refresh is new,
969
+ # and a refresh asks no validator, so a token without an `issuer` would be presented to whatever
970
+ # authorization server discovery names now. Refusing it sends the transport back through the grant,
971
+ # which does ask.
972
+ def ensure_refresh_token_issuer_recorded!
973
+ return if provider_authorization_flow == :authorization_code
974
+ return unless read_token("issuer").nil?
975
+
976
+ raise AuthorizationError, "Cannot refresh: the stored tokens record no issuer; re-authorization is required."
977
+ end
978
+
761
979
  def ensure_refreshable_client_information!(client_info, as_metadata:)
762
980
  stored_issuer = client_info_required_value(client_info, "issuer")
763
981
  return if stored_issuer.nil?
@@ -886,7 +1104,8 @@ module MCP
886
1104
  def resolve_scope(scope:, prm:)
887
1105
  return scope if scope && !scope.empty?
888
1106
 
889
- supported = prm["scopes_supported"]
1107
+ # `prm` is nil on the legacy path, where nothing advertises scopes.
1108
+ supported = prm && prm["scopes_supported"]
890
1109
  return supported.join(" ") if supported.is_a?(Array) && !supported.empty?
891
1110
 
892
1111
  return @provider.scope if @provider.scope && !@provider.scope.empty?
@@ -948,6 +1167,31 @@ module MCP
948
1167
  @provider.authorization_flow
949
1168
  end
950
1169
 
1170
+ # Parameters the provider adds to every token request it makes (RFC 6749 Section 8.2 leaves room for them;
1171
+ # Auth0's `audience` is the usual one). Duck-typed like `authorization_flow`, so a provider without the method,
1172
+ # or one returning `nil`, adds nothing.
1173
+ # A bad value raises `InvalidTokenRequestParamsError`, as the provider constructors do.
1174
+ def provider_token_request_params
1175
+ return {} unless @provider.respond_to?(:token_request_params)
1176
+
1177
+ params = @provider.token_request_params
1178
+ return {} if params.nil?
1179
+
1180
+ problem = self.class.token_request_params_problem(params)
1181
+ raise InvalidTokenRequestParamsError, "The provider's token_request_params #{problem}" if problem
1182
+
1183
+ params
1184
+ end
1185
+
1186
+ # The Client ID Metadata Document URL, when the provider has one. Only `Provider` exposes the reader
1187
+ # (CIMD replaces Dynamic Client Registration on the authorization-code flow), while `refresh!` serves
1188
+ # every provider that holds a `refresh_token`, so the read is duck-typed like `authorization_flow`.
1189
+ def provider_client_id_metadata_document_url
1190
+ return unless @provider.respond_to?(:client_id_metadata_document_url)
1191
+
1192
+ @provider.client_id_metadata_document_url
1193
+ end
1194
+
951
1195
  def build_authorization_url(as_metadata:, client_id:, scope:, state:, code_challenge:, resource:)
952
1196
  authorization_endpoint = as_metadata["authorization_endpoint"]
953
1197
  unless authorization_endpoint
@@ -962,16 +1206,30 @@ module MCP
962
1206
  "Authorization server metadata `authorization_endpoint` is not a valid URI: #{e.message}."
963
1207
  end
964
1208
 
965
- params = URI.decode_www_form(uri.query.to_s)
966
- params << ["response_type", "code"]
967
- params << ["client_id", client_id]
968
- params << ["redirect_uri", @provider.redirect_uri]
969
- params << ["code_challenge", code_challenge]
970
- params << ["code_challenge_method", "S256"]
971
- params << ["state", state]
972
- params << ["scope", scope] if scope
973
- params << ["resource", resource] if resource
974
- uri.query = URI.encode_www_form(params)
1209
+ # A parameter the flow sets replaces any of the same name the endpoint URL already carries.
1210
+ # RFC 6749 Section 3.1 forbids sending a parameter twice, and which of two values a server would honor is
1211
+ # its own choice; on the legacy path the endpoint URL is served by the MCP server, whose query must not speak
1212
+ # for the client's `client_id`, `redirect_uri`, `code_challenge`, or `resource`.
1213
+ # Other parameters in the URL are kept, as the TypeScript SDK's `searchParams.set` keeps them; that includes
1214
+ # a `scope` when the flow has none, since an authorization server may set a default scope there.
1215
+ # RFC 9101 `request` and `request_uri` are dropped as well, though the flow sets neither: a server takes
1216
+ # the whole authorization request from the object they carry, over every parameter in the query, and both are
1217
+ # the client's to send, never an endpoint URL's to supply.
1218
+ own_params = [
1219
+ ["response_type", "code"],
1220
+ ["client_id", client_id],
1221
+ ["redirect_uri", @provider.redirect_uri],
1222
+ ["code_challenge", code_challenge],
1223
+ ["code_challenge_method", "S256"],
1224
+ ["state", state],
1225
+ ]
1226
+ own_params << ["scope", scope] if scope
1227
+ own_params << ["resource", resource] if resource
1228
+ dropped_names = own_params.map(&:first) + ["request", "request_uri"]
1229
+
1230
+ params = URI.decode_www_form(uri.query.to_s).reject { |name, _value| dropped_names.include?(name) }
1231
+ uri.query = URI.encode_www_form(params + own_params)
1232
+
975
1233
  uri
976
1234
  end
977
1235
 
@@ -997,9 +1255,12 @@ module MCP
997
1255
  post_to_token_endpoint(as_metadata: as_metadata, client_info: client_info, form: form)
998
1256
  end
999
1257
 
1000
- # Submits a form-encoded request to the token endpoint, applying
1001
- # the client authentication method advertised in `client_information` and
1002
- # adding `client_id` (and `client_secret` when not using HTTP Basic).
1258
+ # Submits a form-encoded token request using the authentication method
1259
+ # stored in `client_information`. The method determines whether client
1260
+ # credentials belong in the form body, a Basic header, or a JWT assertion.
1261
+ # A provider's `token_request_params` go underneath the flow's own parameters,
1262
+ # which therefore win, and are refused before the request is sent when they name
1263
+ # a reserved parameter or are not a Hash of Strings.
1003
1264
  def post_to_token_endpoint(as_metadata:, client_info:, form:)
1004
1265
  client_id = client_info_required_value(client_info, "client_id")
1005
1266
  unless client_id
@@ -1009,13 +1270,15 @@ module MCP
1009
1270
 
1010
1271
  client_secret = client_info_required_value(client_info, "client_secret")
1011
1272
  token_endpoint_auth_method = client_info_value(client_info, "token_endpoint_auth_method")
1273
+ form = provider_token_request_params.merge(form)
1012
1274
 
1013
- form = if token_endpoint_auth_method == "private_key_jwt"
1014
- # RFC 7523 Section 2.2 JWT client assertion for the `private_key_jwt` method of
1015
- # the `io.modelcontextprotocol/oauth-client-credentials` extension (SEP-1046).
1016
- # The client identity travels in the assertion's `iss`/`sub` claims, so `client_id` is
1017
- # omitted from the body per RFC 7521 Section 4.2 (the `client_assertion` conveys the client identity).
1018
- # The audience is the issuer identifier that `ensure_issuer_matches!` already byte-validated.
1275
+ # Apply one client authentication method per request (RFC 6749 Section 2.3).
1276
+ headers = {}
1277
+ form = case token_endpoint_auth_method
1278
+ when "private_key_jwt"
1279
+ # The assertion identifies the client through its `iss` and `sub`
1280
+ # claims, so the body needs no separate `client_id` (RFC 7521 Section 4.2).
1281
+ # Use the issuer already checked by `ensure_issuer_matches!` as the audience.
1019
1282
  unless @provider.respond_to?(:client_assertion)
1020
1283
  raise AuthorizationError,
1021
1284
  "token_endpoint_auth_method is private_key_jwt but the provider does not " \
@@ -1026,22 +1289,24 @@ module MCP
1026
1289
  "client_assertion_type" => JWTClientAssertion::ASSERTION_TYPE,
1027
1290
  "client_assertion" => @provider.client_assertion(audience: as_metadata["issuer"]),
1028
1291
  )
1292
+ when "client_secret_post"
1293
+ # Send the client ID and available secret in the form body.
1294
+ body = form.merge("client_id" => client_id)
1295
+ body["client_secret"] = client_secret if client_secret
1296
+ body
1029
1297
  else
1030
- form.merge("client_id" => client_id)
1031
- end
1032
-
1033
- headers = {}
1034
- if client_secret
1035
- case token_endpoint_auth_method
1036
- when "client_secret_post"
1037
- form["client_secret"] = client_secret
1038
- when "none"
1039
- # Public client; no credential.
1040
- else
1041
- # RFC 6749 §2.3.1 recommends Basic for confidential clients and
1042
- # both Python and TypeScript SDKs default here when
1043
- # the authentication method is not explicitly stored.
1298
+ if client_secret && token_endpoint_auth_method != "none"
1299
+ # Basic is also the fallback when a secret is present but no method
1300
+ # is stored. A body `client_id` is optional (RFC 6749 Section 3.2.1);
1301
+ # omit it because some servers treat it alongside Basic as a second
1302
+ # authentication method and reject the request with `invalid_request`.
1044
1303
  headers["Authorization"] = "Basic " + basic_auth_credentials(client_id, client_secret)
1304
+ form
1305
+ else
1306
+ # With `none` or no secret, identify the client using `client_id`.
1307
+ # This is required for unauthenticated authorization-code exchanges
1308
+ # (RFC 6749 Section 3.2.1).
1309
+ form.merge("client_id" => client_id)
1045
1310
  end
1046
1311
  end
1047
1312
 
@@ -1059,11 +1324,7 @@ module MCP
1059
1324
  end
1060
1325
 
1061
1326
  if response.status < 200 || response.status >= 300
1062
- if token_endpoint_error_code(response) == "invalid_grant"
1063
- raise InvalidGrantError, "Token endpoint rejected the grant: invalid_grant."
1064
- end
1065
-
1066
- raise AuthorizationError, "Token endpoint returned status #{response.status}."
1327
+ raise token_endpoint_error(response)
1067
1328
  end
1068
1329
 
1069
1330
  parsed = begin
@@ -1084,17 +1345,41 @@ module MCP
1084
1345
  parsed
1085
1346
  end
1086
1347
 
1087
- # Extracts the `error` code from an RFC 6749 §5.2 error response body
1088
- # when one is parseable. Returns nil on any parse failure or when
1089
- # the body is not JSON.
1090
- def token_endpoint_error_code(response)
1091
- body = response_body_string(response).to_s
1092
- return if body.empty?
1348
+ # Surface only RFC 6749 §5.2 diagnostic fields, never the raw response,
1349
+ # which may contain tokens or other credentials. Classify the original
1350
+ # code so sanitization cannot turn malformed input into invalid_grant.
1351
+ def token_endpoint_error(response)
1352
+ message = "Token endpoint returned status #{response.status}."
1353
+ error_class = AuthorizationError
1354
+ parsed = JSON.parse(response_body_string(response))
1355
+ parsed = {} unless parsed.is_a?(Hash)
1356
+
1357
+ error_class = parsed["error"] == "invalid_grant" ? InvalidGrantError : AuthorizationError
1358
+ error = bounded_diagnostic(parsed["error"], limit: TOKEN_ENDPOINT_ERROR_MAX_LENGTH)
1359
+ description = bounded_diagnostic(parsed["error_description"], limit: TOKEN_ENDPOINT_ERROR_DESCRIPTION_MAX_LENGTH)
1360
+ message += " #{[error, description].compact.join(": ")}" if error || description
1361
+
1362
+ error_class.new(message, http_status: response.status, error: error, error_description: description)
1363
+ rescue StandardError
1364
+ # Diagnostics must not mask the endpoint failure or change refresh recovery.
1365
+ error_class.new("Token endpoint returned status #{response.status}.", http_status: response.status)
1366
+ end
1367
+
1368
+ def bounded_diagnostic(value, limit:)
1369
+ return unless value.is_a?(String)
1093
1370
 
1094
- parsed = JSON.parse(body)
1095
- parsed["error"] if parsed.is_a?(Hash)
1096
- rescue JSON::ParserError
1097
- nil
1371
+ # RFC 6749 permits printable ASCII except double quotes and backslashes in token endpoint error fields.
1372
+ # Replace other characters to keep text received off the network on one log line.
1373
+ value = value.scrub(" ").gsub(/[^\x20-\x21\x23-\x5B\x5D-\x7E]/, " ").strip
1374
+ return if value.empty?
1375
+
1376
+ value.length > limit ? "#{value[0, limit - 3]}..." : value
1377
+ end
1378
+
1379
+ # A candidate URL as it goes into a failure string: redacted, and cut so a URL the server chose cannot
1380
+ # grow the message without limit.
1381
+ def reported_url(url)
1382
+ bounded_diagnostic(Discovery.redact_url(url), limit: METADATA_URL_MAX_LENGTH)
1098
1383
  end
1099
1384
 
1100
1385
  # Per RFC 6749 Section 2.3.1, the `client_id` and `client_secret` MUST be
@@ -1162,22 +1447,18 @@ module MCP
1162
1447
  @http_client ||= @http_client_factory.call
1163
1448
  end
1164
1449
 
1165
- # Deliberately built without redirect-following middleware. Every destination check in
1166
- # this class runs against the URL as written, before the request goes out, so a connection
1167
- # that transparently followed a `3xx` would let a server reach a host the checks just refused.
1168
- # A caller passing `http_client_factory:` takes on that responsibility: add redirect following here
1169
- # and the guards above only cover the first hop.
1170
- #
1171
- # `Accept-Encoding` is deliberately left unset. `Net::HTTP::GenericRequest` negotiates it and decodes
1172
- # the response only while the caller has not claimed that header; assigning it turns `decode_content` off,
1173
- # which would silently move `BoundedBody`'s cap onto compressed bytes and let a small body expand past it
1174
- # after the check.
1450
+ # A connection supplied through `http_client_factory:` replaces this one, the provider's customizer and
1451
+ # `RequestedOriginGuard` included, so that caller takes on the redirect responsibility described on
1452
+ # `build_http_client`; `bounded_request` caps its responses all the same.
1175
1453
  def default_http_client
1176
- require "faraday"
1454
+ self.class.build_http_client(provider_http_client_customizer)
1455
+ end
1177
1456
 
1178
- Faraday.new do |faraday|
1179
- faraday.headers["Accept"] = "application/json"
1180
- end
1457
+ # `nil` for a provider that predates the hook or leaves it unset.
1458
+ def provider_http_client_customizer
1459
+ return unless @provider.respond_to?(:http_client_customizer)
1460
+
1461
+ @provider.http_client_customizer
1181
1462
  end
1182
1463
 
1183
1464
  def response_body_string(response)