Support Client ID Metadata Documents in OAuth client

## Motivation and Context

The MCP 2025-11-25 authorization specification and `draft-ietf-oauth-client-id-metadata-document-00` define
Client ID Metadata Documents (CIMD): a client publishes its OAuth metadata at an HTTPS URL and uses that URL
as the OAuth `client_id` instead of going through Dynamic Client Registration. The Python and TypeScript SDKs
already implement this; the Ruby SDK now reaches parity.

The change adds:

- `MCP::Client::OAuth::Provider` accepts an optional `client_id_metadata_document_url:` keyword.
- A new `Discovery.client_id_metadata_document_url?` validator enforces structural requirements.
  Spec-required: `https` scheme, a non-root path, and no fragment, userinfo, or `.`/`..` segments
  (including the percent-encoded form `%2E`). Stricter than the draft as an SDK policy: query strings
  are also rejected, because different encodings of the same query would yield distinct `client_id` strings for
  the same logical document. The loopback `http` carve-out used for discovery URLs does not extend to CIMD URLs,
  since the value is sent verbatim to the authorization server as the OAuth `client_id` and travels off-loopback.
  Validation failures raise `Provider::InvalidClientIDMetadataDocumentURLError`.
- `Flow#ensure_client_registered` routes through CIMD only when the authorization server advertises
  `client_id_metadata_document_supported` as JSON `boolean true`; truthy non-boolean values
  (string `"true"`, `"false"`, etc.) fall back to DCR, matching the gating in the Python and TypeScript SDKs.
- The CIMD `client_id` is NOT persisted to storage. AS support is re-read on every flow so a server
  that later drops CIMD support stops receiving the stale URL. Pre-registered `client_information`
  continues to win over CIMD when both are available.
- `Flow#refresh!` reconstructs the CIMD `client_id` from live AS metadata when refreshing tokens obtained via CIMD.
  When support has been withdrawn and no other identity is stored, it raises a clear `AuthorizationError` rather than
  sending a `client_id` the authorization server no longer recognises.
- The Provider docstring and README OAuth section explain that DCR `client_metadata` and the JSON document served at
  the CIMD URL are separate artifacts: DCR metadata MUST NOT include `client_id`, while the CIMD document MUST include
  `client_id` set to the URL, `client_name`, and `redirect_uris` covering `redirect_uri`.
- `auth/basic-cimd` is removed from `conformance/expected_failures.yml`.

## How Has This Been Tested?

`Discovery` tests cover: https with path accepted; non-https rejected (http, ftp, file); root and empty path rejected;
fragment, query, and userinfo rejected; dot segments rejected including the percent-encoded form `%2E`; nil, empty,
and malformed inputs rejected.

`Provider` tests cover: the default `nil`; rejection of http URLs (loopback included); non-https schemes;
root and empty path; fragment; query; userinfo; and dot segments.

`Flow#run!` tests cover: skip DCR when the authorization server advertises CIMD and the provider has a URL;
fall back to DCR when the authorization server does not advertise support; fall back to DCR when the value is
the string `"false"` or `"true"`; pre-registered `client_information` wins over CIMD; the CIMD `client_id` is not
persisted to storage; a second flow against an authorization server that has dropped CIMD support recovers via DCR.

`Flow#refresh!` tests cover: refresh reconstructs the CIMD `client_id` without a stored `client_information`;
refresh raises when the authorization server no longer advertises CIMD support; stored `client_information`
takes precedence over the CIMD URL during refresh.

Conformance: `auth/basic-cimd` now passes 12/12 with no warnings. `bundle exec rake test`, `bundle exec rake rubocop`,
and `bundle exec rake conformance` are all green.

## Breaking Changes

None. The `client_id_metadata_document_url:` keyword is purely opt-in and defaults to `nil`.
When the keyword is omitted, the DCR flow is unchanged. Existing OAuth users see no behaviour change.
The CIMD path is only entered when both the user explicitly configures a URL and the authorization server
advertises support via `client_id_metadata_document_supported: true`.
This commit is contained in:
Koichi ITO 2026-05-25 02:42:13 +09:00
commit 355c904899
9 changed files with 727 additions and 7 deletions

View file

@ -1958,6 +1958,17 @@ Optional keyword arguments:
- `scope`: Space-separated scopes to request when the server's `WWW-Authenticate` does not specify one.
- `storage`: Object responding to `tokens`, `save_tokens(t)`, `client_information`, `save_client_information(info)`. Defaults to `MCP::Client::OAuth::InMemoryStorage`,
which keeps credentials in process memory only.
- `client_id_metadata_document_url`: URL where you publish a Client ID Metadata Document
(`draft-ietf-oauth-client-id-metadata-document` and the MCP authorization specification).
When the authorization server advertises `client_id_metadata_document_supported: true`,
the SDK uses this URL as the OAuth `client_id` and skips Dynamic Client Registration.
Spec-required: the URL MUST be `https://` with a non-root path and MUST NOT include a fragment,
userinfo, or `.`/`..` segments. The SDK additionally rejects query strings (the draft only marks
them SHOULD NOT include, but the SDK refuses to send any) for `client_id` stability.
Any of these failures raise `Provider::InvalidClientIDMetadataDocumentURLError`. The CIMD document
served at the URL is a separate JSON artifact from the `client_metadata` keyword above:
the DCR `client_metadata` MUST NOT include `client_id`, while the CIMD document MUST include
`client_id` set to the document URL, `client_name`, and `redirect_uris` covering `redirect_uri`.
To persist credentials across restarts, supply your own storage:

View file

@ -19,6 +19,11 @@ unless scenario && server_url
abort("Usage: MCP_CONFORMANCE_SCENARIO=<scenario> ruby conformance/client.rb <server-url>")
end
# URL the conformance harness expects to see as the OAuth `client_id` for the `auth/basic-cimd` scenario
# when the AS advertises `client_id_metadata_document_supported`. The harness does not fetch the document,
# only matches the value, so the URL does not need to resolve.
CONFORMANCE_CIMD_URL = "https://conformance-test.local/client-metadata.json"
# The conformance harness optionally injects scenario-specific data via
# the `MCP_CONFORMANCE_CONTEXT` environment variable as a JSON document. The shape is
# defined by the harness, not the MCP spec, and has varied between versions:
@ -50,7 +55,7 @@ end
# non-interactively against the conformance test's auth server. The conformance
# `/authorize` endpoint redirects synchronously to `redirect_uri` with
# `code=test-auth-code`, so we follow it manually instead of opening a browser.
def build_oauth_provider(context)
def build_oauth_provider(context, scenario:)
callback_holder = {}
redirect_uri = "http://localhost:0/callback"
@ -90,10 +95,11 @@ def build_oauth_provider(context)
redirect_handler: redirect_handler,
callback_handler: callback_handler,
storage: storage,
client_id_metadata_document_url: (scenario == "auth/basic-cimd" ? CONFORMANCE_CIMD_URL : nil),
)
end
oauth = scenario.start_with?("auth/") ? build_oauth_provider(conformance_context) : nil
oauth = scenario.start_with?("auth/") ? build_oauth_provider(conformance_context, scenario: scenario) : nil
transport = MCP::Client::HTTP.new(url: server_url, oauth: oauth)
client = MCP::Client.new(transport: transport)
client.connect(client_info: { name: "ruby-sdk-conformance-client", version: MCP::VERSION })

View file

@ -5,7 +5,6 @@ client:
# TODO: Elicitation not implemented in Ruby client.
- elicitation-sep1034-client-defaults
# TODO: Remaining OAuth/auth scenarios not yet implemented in Ruby client.
- auth/basic-cimd
- auth/scope-step-up
- auth/2025-03-26-oauth-metadata-backcompat
- auth/2025-03-26-oauth-endpoint-fallback

View file

@ -183,6 +183,50 @@ module MCP
false
end
# Returns true when `url` satisfies the structural requirements for
# a Client ID Metadata Document URL per the MCP 2025-11-25
# authorization specification and `draft-ietf-oauth-client-id-metadata-document-00`.
#
# Spec-required:
#
# - scheme MUST be `https` (the loopback-`http` carve-out used for discovery does not apply:
# the document URL is sent verbatim to the authorization server as the OAuth `client_id`
# and travels off-loopback)
# - host MUST be present
# - path MUST be non-empty and MUST NOT be the root (`/`); the document is a discrete resource,
# not the origin
# - URL MUST NOT carry a fragment or userinfo: a fragment is not sent to the server, and userinfo
# would leak credentials into every `client_id` log line
# - path MUST be already free of `.` / `..` dot segments after percent-decoding, so two URLs with
# the same effective path do not produce different `client_id` strings
#
# SDK policy (stricter than the draft):
#
# - URL MUST NOT carry a query string. The draft marks query components only SHOULD NOT include,
# but different encodings of the same query (`?a=1&b=2` vs `?b=2&a=1`) would yield distinct
# `client_id` values for the same logical document.
def client_id_metadata_document_url?(url)
return false if url.nil? || url.to_s.empty?
uri = URI.parse(url.to_s)
return false unless uri.scheme&.downcase == "https"
return false if uri.host.nil? || uri.host.empty?
return false unless uri.fragment.nil?
return false unless uri.query.nil?
return false if uri.respond_to?(:user) && (uri.user || uri.password)
path = uri.path.to_s
return false if path.empty? || path == "/"
decoded = path.gsub(/%2[eE]/, ".")
segments = decoded.split("/", -1)
return false if segments.any? { |segment| segment == "." || segment == ".." }
true
rescue URI::InvalidURIError
false
end
# Like `canonicalize_url` but also strips query string, fragment, and
# userinfo. This variant is used for identity comparison against
# the request URL Faraday actually sends, which differs from the value

View file

@ -104,8 +104,16 @@ module MCP
refresh_token = read_token("refresh_token")
raise AuthorizationError, "Cannot refresh: no refresh_token in provider storage." unless refresh_token
client_info = @provider.client_information
unless client_info.is_a?(Hash) && client_info_required_value(client_info, "client_id")
stored_client_info = @provider.client_information
have_stored_client_info = stored_client_info.is_a?(Hash) && client_info_required_value(stored_client_info, "client_id")
# A CIMD-configured provider stores no `client_information` on purpose
# (the CIMD URL is re-resolved against the live AS metadata on every flow).
# Allow refresh to proceed in that case so the `refresh_token` obtained via
# the CIMD flow remains usable.
have_cimd_url = !@provider.client_id_metadata_document_url.nil?
unless have_stored_client_info || have_cimd_url
raise AuthorizationError, "Cannot refresh: no client_information in provider storage."
end
@ -126,6 +134,18 @@ module MCP
ensure_issuer_matches!(expected: authorization_server, returned: as_metadata["issuer"])
ensure_secure_endpoints!(as_metadata)
client_info = if have_stored_client_info
# Pre-registered / DCR-issued `client_information` always wins: if the user picked an explicit identity,
# do not silently swap it for the CIMD URL even when the AS also advertises CIMD support.
stored_client_info
elsif as_metadata["client_id_metadata_document_supported"] == true
{ "client_id" => @provider.client_id_metadata_document_url }
else
raise AuthorizationError,
"Cannot refresh: provider has a CIMD URL but the authorization server no longer advertises " \
"`client_id_metadata_document_supported: true`."
end
new_tokens = exchange_refresh_token(
as_metadata: as_metadata,
client_info: client_info,
@ -285,6 +305,24 @@ module MCP
existing = @provider.client_information
return existing if existing.is_a?(Hash) && client_info_required_value(existing, "client_id")
# Per the MCP authorization specification and `draft-ietf-oauth-client-id-metadata-document`,
# if the authorization server advertises Client ID Metadata Document support and the provider has
# a CIMD URL configured, use the URL as the OAuth `client_id` and skip Dynamic Client Registration.
#
# The `== true` comparison is intentional: only a JSON `boolean` `true` opts the flow in.
# A string `"false"`, an empty Hash, or any other truthy value MUST NOT be treated as CIMD support,
# otherwise a misconfigured AS could trick the client into using the CIMD `client_id` against
# a server that has not actually adopted it.
#
# The CIMD `client_id` is NOT persisted to storage. The AS may later stop advertising CIMD support
# (or the operator may rotate the CIMD URL), and a stale `client_information` entry would otherwise
# keep sending the old CIMD URL forever. Re-evaluating on every flow re-reads the current AS metadata
# and the current `provider.client_id_metadata_document_url`.
cimd_url = @provider.client_id_metadata_document_url
if cimd_url && as_metadata["client_id_metadata_document_supported"] == true
return { "client_id" => cimd_url }
end
registration_endpoint = as_metadata["registration_endpoint"]
unless registration_endpoint
raise AuthorizationError,

View file

@ -25,6 +25,16 @@ module MCP
# - `storage` - Object responding to `tokens`, `save_tokens(tokens)`,
# `client_information`, and `save_client_information(info)`. Defaults to
# an `InMemoryStorage`.
# - `client_id_metadata_document_url` - URL where the client publishes its Client ID Metadata Document
# (`draft-ietf-oauth-client-id-metadata-document-00` and the MCP authorization specification).
# When the authorization server advertises `client_id_metadata_document_supported: true`,
# the SDK uses this URL as the OAuth `client_id` and skips Dynamic Client Registration.
# Spec-required: `https://` scheme, a non-root path, and no fragment, userinfo, or `.`/`..` segments.
# The SDK additionally refuses to send query strings (the draft marks them only SHOULD NOT include,
# but different encodings of the same query would yield different `client_id` strings for the same document).
# The document served at the URL is a separate JSON artifact from the `client_metadata` keyword:
# DCR `client_metadata` MUST NOT include `client_id`, while the CIMD document MUST include `client_id` set
# to the URL, `client_name`, and `redirect_uris` covering `redirect_uri`.
class Provider
# Raised when `Provider#initialize` is called with a `redirect_uri` that
# is neither HTTPS nor a loopback `http://` URL, per the MCP
@ -38,12 +48,21 @@ module MCP
# runtime; failing at construction surfaces the bug earlier.
class UnregisteredRedirectURIError < ArgumentError; end
# Raised when `client_id_metadata_document_url` is provided but does not meet
# the structural requirements for a Client ID Metadata Document URL:
# HTTPS, non-root path, and no fragment, query, userinfo, or `.`/`..` segments.
# The CIMD URL is sent to the authorization server as the OAuth `client_id`,
# so the same Communication Security guarantee that protects the redirect URI
# applies and the value must unambiguously identify the document.
class InvalidClientIDMetadataDocumentURLError < ArgumentError; end
attr_reader :client_metadata,
:redirect_uri,
:scope,
:storage,
:redirect_handler,
:callback_handler
:callback_handler,
:client_id_metadata_document_url
def initialize(
client_metadata:,
@ -51,7 +70,8 @@ module MCP
redirect_handler:,
callback_handler:,
scope: nil,
storage: nil
storage: nil,
client_id_metadata_document_url: nil
)
unless Discovery.secure_url?(redirect_uri)
raise InsecureRedirectURIError,
@ -66,12 +86,20 @@ module MCP
"(got #{registered.inspect}); otherwise the authorization server will reject the authorization request."
end
if client_id_metadata_document_url && !Discovery.client_id_metadata_document_url?(client_id_metadata_document_url)
raise InvalidClientIDMetadataDocumentURLError,
"client_id_metadata_document_url #{client_id_metadata_document_url.inspect} must be an https URL " \
"with a non-root path and no fragment, query, userinfo, or `.`/`..` segments, " \
"per the MCP authorization specification and `draft-ietf-oauth-client-id-metadata-document`."
end
@client_metadata = client_metadata
@redirect_uri = redirect_uri
@redirect_handler = redirect_handler
@callback_handler = callback_handler
@scope = scope
@storage = storage || InMemoryStorage.new
@client_id_metadata_document_url = client_id_metadata_document_url
end
def access_token

View file

@ -367,6 +367,68 @@ module MCP
refute(Discovery.secure_url?("not a url"))
end
def test_client_id_metadata_document_url_accepts_https_with_path
assert(Discovery.client_id_metadata_document_url?("https://app.example.com/client-metadata.json"))
assert(Discovery.client_id_metadata_document_url?("https://app.example.com/path/to/cm"))
assert(Discovery.client_id_metadata_document_url?("https://app.example.com:8443/cm"))
end
def test_client_id_metadata_document_url_accepts_boundary_forms
# An uppercase scheme is `https` after case folding (URIs are scheme-insensitive, RFC 3986 Section 3.1).
assert(Discovery.client_id_metadata_document_url?("HTTPS://app.example.com/cm"))
# A trailing slash and consecutive slashes are non-root, non-dot paths.
# RFC 3986 `remove_dot_segments` does not collapse them, so they remain
# stable `client_id` strings rather than aliasing another URL.
assert(Discovery.client_id_metadata_document_url?("https://app.example.com/cm/"))
assert(Discovery.client_id_metadata_document_url?("https://app.example.com//cm"))
# The default https port is equivalent to omitting it; either form is a valid origin.
assert(Discovery.client_id_metadata_document_url?("https://app.example.com:443/cm"))
# IPv6 literal hosts and Punycode (IDN) hosts are ordinary hosts.
assert(Discovery.client_id_metadata_document_url?("https://[2001:db8::1]/cm"))
assert(Discovery.client_id_metadata_document_url?("https://[::1]/cm"))
assert(Discovery.client_id_metadata_document_url?("https://xn--e1afmkfd.example.com/cm"))
end
def test_client_id_metadata_document_url_rejects_non_https_schemes
refute(Discovery.client_id_metadata_document_url?("http://localhost/cm"))
refute(Discovery.client_id_metadata_document_url?("http://app.example.com/cm"))
refute(Discovery.client_id_metadata_document_url?("ftp://app.example.com/cm"))
refute(Discovery.client_id_metadata_document_url?("file:///cm"))
end
def test_client_id_metadata_document_url_rejects_root_and_empty_path
refute(Discovery.client_id_metadata_document_url?("https://app.example.com"))
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/"))
end
def test_client_id_metadata_document_url_rejects_fragment_query_userinfo
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/cm#frag"))
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/cm?x=1"))
refute(Discovery.client_id_metadata_document_url?("https://user:pass@app.example.com/cm"))
refute(Discovery.client_id_metadata_document_url?("https://user@app.example.com/cm"))
end
def test_client_id_metadata_document_url_rejects_dot_segments
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/./cm"))
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/a/../cm"))
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/cm/."))
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/cm/.."))
# Percent-encoded `.` would otherwise let `%2E` and `.` produce
# different `client_id` values for the same document.
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/%2E/cm"))
refute(Discovery.client_id_metadata_document_url?("https://app.example.com/%2e/cm"))
end
def test_client_id_metadata_document_url_rejects_nil_or_empty_or_malformed
refute(Discovery.client_id_metadata_document_url?(nil))
refute(Discovery.client_id_metadata_document_url?(""))
refute(Discovery.client_id_metadata_document_url?("not a url"))
refute(Discovery.client_id_metadata_document_url?("https://"))
end
def test_resource_covers_blocks_percent_encoded_dot_segment_bypass
server = Discovery.canonicalize_url("https://srv.example.com/api/%2e%2e/mcp")
prm = Discovery.canonicalize_url("https://srv.example.com/api")

View file

@ -547,6 +547,276 @@ module MCP
assert_not_requested(:post, "#{@auth_base}/register")
end
def test_run_skips_dcr_when_as_supports_cimd_and_provider_has_cimd_url
# When the AS advertises Client ID Metadata Document support and the provider was configured with a CIMD URL,
# the SDK uses the URL as the OAuth `client_id` and does not call /register.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: true,
),
)
stub_request(:post, "#{@auth_base}/register").to_raise(StandardError.new("DCR should not be called."))
captured_authorization_url = nil
state_holder = {}
provider = Provider.new(
client_metadata: {
redirect_uris: ["http://localhost:0/callback"],
grant_types: ["authorization_code"],
response_types: ["code"],
token_endpoint_auth_method: "none",
},
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(url) {
captured_authorization_url = url
state_holder[:state] = URI.decode_www_form(url.query).to_h.fetch("state")
},
callback_handler: -> { ["test-auth-code", state_holder[:state]] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
Flow.new(provider: provider).run!(server_url: @server_url, resource_metadata_url: @prm_url)
assert_not_requested(:post, "#{@auth_base}/register")
query = URI.decode_www_form(captured_authorization_url.query).to_h
assert_equal("https://app.example.com/client-metadata.json", query["client_id"])
assert_requested(:post, "#{@auth_base}/token") do |req|
URI.decode_www_form(req.body).to_h["client_id"] == "https://app.example.com/client-metadata.json"
end
# The CIMD URL is NOT persisted to storage: AS metadata is re-read on every flow,
# so a later AS that no longer advertises CIMD will not be sent a stale CIMD `client_id`.
assert_nil(provider.client_information)
end
def test_run_falls_back_to_dcr_when_provider_has_cimd_url_but_as_does_not_advertise_support
# The provider may carry a CIMD URL across multiple servers; if a particular AS does not advertise CIMD support,
# the SDK must still register via DCR rather than send an unsupported `client_id`.
state_holder = {}
provider = Provider.new(
client_metadata: {
redirect_uris: ["http://localhost:0/callback"],
grant_types: ["authorization_code"],
response_types: ["code"],
token_endpoint_auth_method: "none",
},
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(url) {
state_holder[:state] = URI.decode_www_form(url.query).to_h.fetch("state")
},
callback_handler: -> { ["test-auth-code", state_holder[:state]] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
Flow.new(provider: provider).run!(server_url: @server_url, resource_metadata_url: @prm_url)
assert_requested(:post, "#{@auth_base}/register")
assert_equal("test-client", provider.client_information["client_id"])
end
def test_run_does_not_enter_cimd_branch_when_support_advertised_as_string_false
# A misconfigured AS that ships `"client_id_metadata_document_supported": "false"`
# is truthy in Ruby. The SDK must NOT route through CIMD on truthy non-boolean values;
# only a JSON `boolean true` opts in.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
registration_endpoint: "#{@auth_base}/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: "false",
),
)
state_holder = {}
provider = Provider.new(
client_metadata: {
redirect_uris: ["http://localhost:0/callback"],
grant_types: ["authorization_code"],
response_types: ["code"],
token_endpoint_auth_method: "none",
},
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(url) {
state_holder[:state] = URI.decode_www_form(url.query).to_h.fetch("state")
},
callback_handler: -> { ["test-auth-code", state_holder[:state]] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
Flow.new(provider: provider).run!(server_url: @server_url, resource_metadata_url: @prm_url)
assert_requested(:post, "#{@auth_base}/register")
assert_equal("test-client", provider.client_information["client_id"])
end
def test_run_does_not_enter_cimd_branch_when_support_advertised_as_string_true
# Mirror of the previous test for the other truthy non-boolean value:
# `"true"` is also a string, not the JSON boolean the spec requires.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
registration_endpoint: "#{@auth_base}/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: "true",
),
)
state_holder = {}
provider = Provider.new(
client_metadata: {
redirect_uris: ["http://localhost:0/callback"],
grant_types: ["authorization_code"],
response_types: ["code"],
token_endpoint_auth_method: "none",
},
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(url) {
state_holder[:state] = URI.decode_www_form(url.query).to_h.fetch("state")
},
callback_handler: -> { ["test-auth-code", state_holder[:state]] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
Flow.new(provider: provider).run!(server_url: @server_url, resource_metadata_url: @prm_url)
assert_requested(:post, "#{@auth_base}/register")
end
def test_run_does_not_persist_cimd_client_id_so_later_flow_recovers_when_as_drops_support
# Regression for the storage side-effect: if the SDK persisted the CIMD URL on the first flow,
# a second flow against an AS that no longer advertises CIMD support would still send the URL as
# the `client_id` and skip DCR. Re-running with the same provider must honour the updated AS metadata.
shared_storage = InMemoryStorage.new
state_holder = {}
provider = Provider.new(
client_metadata: {
redirect_uris: ["http://localhost:0/callback"],
grant_types: ["authorization_code"],
response_types: ["code"],
token_endpoint_auth_method: "none",
},
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(url) {
state_holder[:state] = URI.decode_www_form(url.query).to_h.fetch("state")
},
callback_handler: -> { ["test-auth-code", state_holder[:state]] },
storage: shared_storage,
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
# First flow: AS supports CIMD, so DCR is skipped.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
registration_endpoint: "#{@auth_base}/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: true,
),
)
stub_request(:post, "#{@auth_base}/register").to_return(
status: 201,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(client_id: "test-client"),
)
Flow.new(provider: provider).run!(server_url: @server_url, resource_metadata_url: @prm_url)
assert_nil(shared_storage.client_information, "CIMD client_id must not be persisted")
# Second flow: AS no longer advertises CIMD. The SDK must register via DCR rather than reuse a stale CIMD URL.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
registration_endpoint: "#{@auth_base}/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
),
)
Flow.new(provider: provider).run!(server_url: @server_url, resource_metadata_url: @prm_url)
assert_requested(:post, "#{@auth_base}/register")
assert_equal("test-client", shared_storage.client_information["client_id"])
end
def test_run_skips_cimd_when_pre_registered_client_information_exists
# Pre-registered `client_information` wins over CIMD: the user explicitly chose a DCR-style identity,
# so neither DCR nor the CIMD URL should overwrite it.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: true,
),
)
stub_request(:post, "#{@auth_base}/register").to_raise(StandardError.new("DCR should not be called."))
captured_authorization_url = nil
state_holder = {}
provider = Provider.new(
client_metadata: {
redirect_uris: ["http://localhost:0/callback"],
grant_types: ["authorization_code"],
response_types: ["code"],
token_endpoint_auth_method: "none",
},
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(url) {
captured_authorization_url = url
state_holder[:state] = URI.decode_www_form(url.query).to_h.fetch("state")
},
callback_handler: -> { ["test-auth-code", state_holder[:state]] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
provider.save_client_information("client_id" => "preregistered-client")
Flow.new(provider: provider).run!(server_url: @server_url, resource_metadata_url: @prm_url)
query = URI.decode_www_form(captured_authorization_url.query).to_h
assert_equal("preregistered-client", query["client_id"])
end
def test_run_uses_basic_auth_when_token_endpoint_auth_method_is_client_secret_basic
state_holder = {}
provider = Provider.new(
@ -876,6 +1146,170 @@ module MCP
assert_equal("saved-rt", provider.tokens["refresh_token"])
end
def test_refresh_uses_cimd_url_as_client_id_when_provider_has_cimd_and_as_supports_it
# Regression: the CIMD branch in `ensure_client_registered` does not persist `client_information`,
# so a refresh call that requires stored client info would always fail after a CIMD-only flow.
# `refresh!` must reconstruct the CIMD `client_id` from live AS metadata + the provider URL on every call.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: true,
),
)
stub_request(:post, "#{@auth_base}/register").to_raise(StandardError.new("DCR should not be called."))
stub_request(:post, "#{@auth_base}/token").with(
body: hash_including(
"grant_type" => "refresh_token",
"refresh_token" => "saved-rt",
"client_id" => "https://app.example.com/client-metadata.json",
),
).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(access_token: "fresh-at", token_type: "Bearer", expires_in: 3600),
)
provider = Provider.new(
client_metadata: { redirect_uris: ["http://localhost:0/callback"] },
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(_url) {},
callback_handler: -> { [nil, nil] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
provider.save_tokens("access_token" => "stale-at", "refresh_token" => "saved-rt")
result = Flow.new(provider: provider).refresh!(
server_url: @server_url,
resource_metadata_url: @prm_url,
)
assert_equal(:refreshed, result)
assert_equal("fresh-at", provider.access_token)
assert_nil(provider.client_information, "refresh must not persist a CIMD client_information entry")
end
def test_refresh_raises_when_provider_has_cimd_url_but_as_no_longer_advertises_support
# If the AS later drops CIMD support and the provider has neither a stored `client_information` nor
# an alternative identity, refresh has no way to authenticate. Fail loudly rather than send a CIMD
# `client_id` the AS no longer recognises.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
registration_endpoint: "#{@auth_base}/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
),
)
provider = Provider.new(
client_metadata: { redirect_uris: ["http://localhost:0/callback"] },
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(_url) {},
callback_handler: -> { [nil, nil] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
provider.save_tokens("access_token" => "stale-at", "refresh_token" => "saved-rt")
error = assert_raises(Flow::AuthorizationError) do
Flow.new(provider: provider).refresh!(server_url: @server_url, resource_metadata_url: @prm_url)
end
assert_match(/client_id_metadata_document_supported/, error.message)
assert_not_requested(:post, "#{@auth_base}/token")
end
def test_refresh_prefers_stored_client_information_over_cimd_url
# Even when both are available, an explicitly stored `client_information` wins.
# CIMD MUST NOT silently override it.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: true,
),
)
stub_request(:post, "#{@auth_base}/token").with(
body: hash_including(
"grant_type" => "refresh_token",
"client_id" => "preregistered-client",
),
).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(access_token: "fresh-at", token_type: "Bearer", expires_in: 3600),
)
provider = Provider.new(
client_metadata: { redirect_uris: ["http://localhost:0/callback"] },
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(_url) {},
callback_handler: -> { [nil, nil] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
provider.save_client_information("client_id" => "preregistered-client")
provider.save_tokens("access_token" => "stale-at", "refresh_token" => "saved-rt")
Flow.new(provider: provider).refresh!(server_url: @server_url, resource_metadata_url: @prm_url)
assert_equal("fresh-at", provider.access_token)
end
def test_refresh_raises_when_cimd_support_advertised_as_string_true
# Mirror of the `run!` strict-boolean tests on the refresh path: a truthy non-boolean value
# such as the string `"true"` must NOT be treated as CIMD support. With no stored `client_information`
# and no genuine CIMD support, refresh has no identity to authenticate with.
stub_request(:get, @as_metadata_url).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: JSON.generate(
issuer: @auth_base,
authorization_endpoint: "#{@auth_base}/authorize",
token_endpoint: "#{@auth_base}/token",
registration_endpoint: "#{@auth_base}/register",
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: "true",
),
)
provider = Provider.new(
client_metadata: { redirect_uris: ["http://localhost:0/callback"] },
redirect_uri: "http://localhost:0/callback",
redirect_handler: ->(_url) {},
callback_handler: -> { [nil, nil] },
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
provider.save_tokens("access_token" => "stale-at", "refresh_token" => "saved-rt")
error = assert_raises(Flow::AuthorizationError) do
Flow.new(provider: provider).refresh!(server_url: @server_url, resource_metadata_url: @prm_url)
end
assert_match(/client_id_metadata_document_supported/, error.message)
assert_not_requested(:post, "#{@auth_base}/token")
end
def test_refresh_raises_when_no_refresh_token
provider = Provider.new(
client_metadata: { redirect_uris: ["http://localhost:0/callback"] },

View file

@ -83,6 +83,104 @@ module MCP
provider = Provider.new(**args)
assert_equal("http://localhost:0/callback", provider.redirect_uri)
end
def test_initialize_defaults_client_id_metadata_document_url_to_nil
provider = Provider.new(**args_for("http://localhost:0/callback"))
assert_nil(provider.client_id_metadata_document_url)
end
def test_initialize_accepts_https_client_id_metadata_document_url
args = args_for("http://localhost:0/callback").merge(
client_id_metadata_document_url: "https://app.example.com/client-metadata.json",
)
provider = Provider.new(**args)
assert_equal(
"https://app.example.com/client-metadata.json",
provider.client_id_metadata_document_url,
)
end
def test_initialize_rejects_http_client_id_metadata_document_url
# The loopback `http` carve-out used for discovery does not extend to the CIMD URL:
# the URL is sent to the AS as the OAuth `client_id` and travels off-loopback,
# so MCP requires `https`.
["http://localhost:8080/client-metadata.json", "http://app.example.com/cm"].each do |uri|
args = args_for("http://localhost:0/callback").merge(client_id_metadata_document_url: uri)
assert_raises(Provider::InvalidClientIDMetadataDocumentURLError, "should reject #{uri}") do
Provider.new(**args)
end
end
end
def test_initialize_rejects_non_https_scheme_client_id_metadata_document_url
["ftp://app.example.com/cm", "file:///cm", "foo://bar/cm"].each do |uri|
args = args_for("http://localhost:0/callback").merge(client_id_metadata_document_url: uri)
assert_raises(Provider::InvalidClientIDMetadataDocumentURLError, "should reject #{uri}") do
Provider.new(**args)
end
end
end
def test_initialize_rejects_client_id_metadata_document_url_without_path
# The CIMD document is a discrete resource, not the origin.
# A bare origin or root-path URL would let two different deployments at
# the same origin shadow each other under one `client_id`.
["https://app.example.com", "https://app.example.com/"].each do |uri|
args = args_for("http://localhost:0/callback").merge(client_id_metadata_document_url: uri)
assert_raises(Provider::InvalidClientIDMetadataDocumentURLError, "should reject #{uri}") do
Provider.new(**args)
end
end
end
def test_initialize_rejects_client_id_metadata_document_url_with_fragment
# A fragment is never sent to the server; embedding one in the `client_id` value
# would make the OAuth `client_id` and the URL the AS dereferences point at different artifacts.
args = args_for("http://localhost:0/callback").merge(
client_id_metadata_document_url: "https://app.example.com/cm#frag",
)
assert_raises(Provider::InvalidClientIDMetadataDocumentURLError) do
Provider.new(**args)
end
end
def test_initialize_rejects_client_id_metadata_document_url_with_query
args = args_for("http://localhost:0/callback").merge(
client_id_metadata_document_url: "https://app.example.com/cm?x=1",
)
assert_raises(Provider::InvalidClientIDMetadataDocumentURLError) do
Provider.new(**args)
end
end
def test_initialize_rejects_client_id_metadata_document_url_with_userinfo
# Embedding credentials in the `client_id` leaks them to every AS
# log line and to the conformance audit trail.
args = args_for("http://localhost:0/callback").merge(
client_id_metadata_document_url: "https://user:pass@app.example.com/cm",
)
assert_raises(Provider::InvalidClientIDMetadataDocumentURLError) do
Provider.new(**args)
end
end
def test_initialize_rejects_client_id_metadata_document_url_with_dot_segments
# `https://x/a/./b` and `https://x/a/b` are RFC 3986 equivalent,
# so accepting both would let one client publish under two `client_id` values.
# Reject `.`/`..` (including percent-encoded `.`).
[
"https://app.example.com/./cm",
"https://app.example.com/a/../cm",
"https://app.example.com/%2E/cm",
].each do |uri|
args = args_for("http://localhost:0/callback").merge(client_id_metadata_document_url: uri)
assert_raises(Provider::InvalidClientIDMetadataDocumentURLError, "should reject #{uri}") do
Provider.new(**args)
end
end
end
end
end
end