Skip to content

Commit 86c2860

Browse files
Updates to conform to section 3.1 of the OAuth 2.1 specification
1 parent 77001c9 commit 86c2860

4 files changed

Lines changed: 221 additions & 4 deletions

File tree

‎src/mcp/client/auth/oauth2.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from collections.abc import AsyncGenerator, Awaitable, Callable
1313
from dataclasses import dataclass, field
1414
from typing import Any, Protocol, get_args
15-
from urllib.parse import quote, urlencode, urljoin, urlparse
15+
from urllib.parse import quote, urljoin, urlparse
1616

1717
import anyio
1818
import httpx2
@@ -56,6 +56,7 @@
5656
from mcp.shared.auth_utils import (
5757
calculate_token_expiry,
5858
check_resource_allowed,
59+
replace_query_params,
5960
resource_url_from_server_url,
6061
)
6162
from mcp.shared.inbound import MCP_PROTOCOL_VERSION_HEADER
@@ -397,6 +398,10 @@ async def _perform_authorization_code_grant(self) -> tuple[str, str]:
397398
auth_base_url = self.context.get_authorization_base_url(self.context.server_url)
398399
auth_endpoint = urljoin(auth_base_url, "/authorize")
399400

401+
# OAuth 2.1 section 3.1: the authorization endpoint URI MUST NOT include a fragment.
402+
if urlparse(auth_endpoint).fragment:
403+
raise OAuthFlowError(f"Authorization endpoint must not include a fragment: {auth_endpoint}")
404+
400405
if not self.context.client_info:
401406
raise OAuthFlowError("No client info available for authorization") # pragma: no cover
402407

@@ -425,7 +430,8 @@ async def _perform_authorization_code_grant(self) -> tuple[str, str]:
425430
if "offline_access" in self.context.client_metadata.scope.split():
426431
auth_params["prompt"] = "consent"
427432

428-
authorization_url = f"{auth_endpoint}?{urlencode(auth_params)}"
433+
# OAuth 2.1 section 3.1: retain the endpoint's query and never send a parameter twice.
434+
authorization_url = replace_query_params(auth_endpoint, auth_params)
429435
with waiting_on_a_person():
430436
await self.context.redirect_handler(authorization_url)
431437
result = await self.context.callback_handler()

‎src/mcp/shared/auth_utils.py‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""Utilities for OAuth 2.0 Resource Indicators (RFC 8707) and PKCE (RFC 7636)."""
22

33
import time
4-
from urllib.parse import urlparse, urlsplit, urlunsplit
4+
from collections.abc import Iterable, Mapping
5+
from urllib.parse import parse_qsl, urlencode, urlparse, urlsplit, urlunsplit
56

67
from pydantic import AnyUrl, HttpUrl
78

@@ -78,3 +79,62 @@ def calculate_token_expiry(expires_in: int | str | None) -> float | None:
7879
return None # pragma: no cover
7980
# Defensive: handle servers that return expires_in as string
8081
return time.time() + int(expires_in)
82+
83+
84+
def add_query_params(url: str, params: Mapping[str, str]) -> str:
85+
"""Append query parameters to a URL, preserving any existing ones.
86+
87+
New parameters are appended after the existing query rather than replacing
88+
keys that are already present, so a key may end up appearing more than once.
89+
The whole query string is re-encoded, which can change how existing
90+
parameters are escaped (e.g. ``%20`` becomes ``+``).
91+
92+
Args:
93+
url: URL to add the parameters to
94+
params: Mapping of parameter names to values to append
95+
96+
Returns:
97+
The URL with the parameters appended to its query string
98+
"""
99+
parts = urlsplit(url)
100+
query = parse_qsl(parts.query, keep_blank_values=True)
101+
query.extend(params.items())
102+
return urlunsplit(parts._replace(query=urlencode(query)))
103+
104+
105+
def remove_query_params(url: str, keys: Iterable[str]) -> str:
106+
"""Remove query parameters from a URL by name.
107+
108+
Every occurrence of each named key is removed; other parameters keep their
109+
original order. The remaining query string is re-encoded, which can change
110+
how those parameters are escaped (e.g. ``%20`` becomes ``+``).
111+
112+
Args:
113+
url: URL to remove the parameters from
114+
keys: Iterable of parameter names to remove
115+
116+
Returns:
117+
The URL without the named query parameters
118+
"""
119+
keys = set(keys)
120+
parts = urlsplit(url)
121+
query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if k not in keys]
122+
return urlunsplit(parts._replace(query=urlencode(query)))
123+
124+
125+
def replace_query_params(url: str, params: Mapping[str, str]) -> str:
126+
"""Set query parameters on a URL, replacing any existing values for those keys.
127+
128+
Other existing parameters are retained in order, and each given key appears
129+
exactly once, after the retained parameters. The whole query string is
130+
re-encoded, which can change how existing parameters are escaped (e.g.
131+
``%20`` becomes ``+``).
132+
133+
Args:
134+
url: URL to set the parameters on
135+
params: Mapping of parameter names to values to set
136+
137+
Returns:
138+
The URL with the given parameters replacing any same-named existing ones
139+
"""
140+
return add_query_params(remove_query_params(url, params), params)

‎tests/client/test_auth.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1785,6 +1785,115 @@ async def test_403_without_a_scope_challenge_is_returned_to_the_caller(
17851785
await auth_flow.asend(response_403)
17861786

17871787

1788+
@pytest.mark.anyio
1789+
async def test_authorization_url_retains_the_endpoint_query_component(oauth_provider: OAuthClientProvider):
1790+
"""Spec-mandated (OAuth 2.1 section 3.1): the authorization endpoint's existing
1791+
application/x-www-form-urlencoded query is retained when the request parameters are added."""
1792+
oauth_provider.context.oauth_metadata = OAuthMetadata(
1793+
issuer=AnyHttpUrl("https://auth.example.com"),
1794+
authorization_endpoint=AnyHttpUrl("https://auth.example.com/authorize?tenant=acme"),
1795+
token_endpoint=AnyHttpUrl("https://auth.example.com/token"),
1796+
)
1797+
oauth_provider.context.client_info = OAuthClientInformationFull(
1798+
client_id="test_client_id",
1799+
redirect_uris=[AnyUrl("http://localhost:3030/callback")],
1800+
)
1801+
1802+
captured_url: str | None = None
1803+
captured_state: str | None = None
1804+
1805+
async def capture_redirect(url: str) -> None:
1806+
nonlocal captured_url, captured_state
1807+
captured_url = url
1808+
captured_state = parse_qs(urlparse(url).query)["state"][0]
1809+
1810+
async def echo_callback() -> AuthorizationCodeResult:
1811+
return AuthorizationCodeResult(code="auth_code", state=captured_state)
1812+
1813+
oauth_provider.context.redirect_handler = capture_redirect
1814+
oauth_provider.context.callback_handler = echo_callback
1815+
1816+
await oauth_provider._perform_authorization_code_grant()
1817+
1818+
assert captured_url is not None
1819+
assert captured_url.count("?") == 1
1820+
parsed = urlparse(captured_url)
1821+
assert parsed.path == "/authorize"
1822+
params = parse_qs(parsed.query)
1823+
assert params["tenant"] == ["acme"]
1824+
assert params["response_type"] == ["code"]
1825+
assert params["state"] == [captured_state]
1826+
1827+
1828+
@pytest.mark.anyio
1829+
async def test_authorization_url_sends_each_client_set_param_once_overriding_the_endpoint_query(
1830+
oauth_provider: OAuthClientProvider,
1831+
):
1832+
"""Spec-mandated (OAuth 2.1 section 3.1): a request parameter MUST NOT be included more
1833+
than once, so client-set values override same-named endpoint query parameters."""
1834+
client_info = OAuthClientInformationFull(
1835+
client_id="test_client_id",
1836+
redirect_uris=[AnyUrl("http://localhost:3030/callback")],
1837+
)
1838+
oauth_provider.context.oauth_metadata = OAuthMetadata(
1839+
issuer=AnyHttpUrl("https://auth.example.com"),
1840+
authorization_endpoint=AnyHttpUrl(
1841+
"https://auth.example.com/authorize?response_type=token&client_id=other&tenant=acme"
1842+
),
1843+
token_endpoint=AnyHttpUrl("https://auth.example.com/token"),
1844+
)
1845+
oauth_provider.context.client_info = client_info
1846+
1847+
captured_url: str | None = None
1848+
captured_state: str | None = None
1849+
1850+
async def capture_redirect(url: str) -> None:
1851+
nonlocal captured_url, captured_state
1852+
captured_url = url
1853+
captured_state = parse_qs(urlparse(url).query)["state"][0]
1854+
1855+
async def echo_callback() -> AuthorizationCodeResult:
1856+
return AuthorizationCodeResult(code="auth_code", state=captured_state)
1857+
1858+
oauth_provider.context.redirect_handler = capture_redirect
1859+
oauth_provider.context.callback_handler = echo_callback
1860+
1861+
await oauth_provider._perform_authorization_code_grant()
1862+
1863+
assert captured_url is not None
1864+
params = parse_qs(urlparse(captured_url).query)
1865+
assert params["response_type"] == ["code"]
1866+
assert params["client_id"] == [client_info.client_id]
1867+
assert params["tenant"] == ["acme"]
1868+
1869+
1870+
@pytest.mark.anyio
1871+
async def test_authorization_endpoint_with_fragment_raises_before_redirecting(oauth_provider: OAuthClientProvider):
1872+
"""Spec-mandated (OAuth 2.1 section 3.1): the authorization endpoint URI MUST NOT include
1873+
a fragment, so a fragment-bearing endpoint fails before any redirect happens."""
1874+
oauth_provider.context.oauth_metadata = OAuthMetadata(
1875+
issuer=AnyHttpUrl("https://auth.example.com"),
1876+
authorization_endpoint=AnyHttpUrl("https://auth.example.com/authorize#frag"),
1877+
token_endpoint=AnyHttpUrl("https://auth.example.com/token"),
1878+
)
1879+
oauth_provider.context.client_info = OAuthClientInformationFull(
1880+
client_id="test_client_id",
1881+
redirect_uris=[AnyUrl("http://localhost:3030/callback")],
1882+
)
1883+
1884+
async def redirect_handler(url: str) -> None:
1885+
raise NotImplementedError
1886+
1887+
async def callback_handler() -> AuthorizationCodeResult:
1888+
raise NotImplementedError
1889+
1890+
oauth_provider.context.redirect_handler = redirect_handler
1891+
oauth_provider.context.callback_handler = callback_handler
1892+
1893+
with pytest.raises(OAuthFlowError):
1894+
await oauth_provider._perform_authorization_code_grant()
1895+
1896+
17881897
@pytest.mark.parametrize(
17891898
(
17901899
"issuer_url",

‎tests/shared/test_auth_utils.py‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@
22

33
from pydantic import HttpUrl
44

5-
from mcp.shared.auth_utils import check_resource_allowed, resource_url_from_server_url
5+
from mcp.shared.auth_utils import (
6+
add_query_params,
7+
check_resource_allowed,
8+
remove_query_params,
9+
replace_query_params,
10+
resource_url_from_server_url,
11+
)
612

713
# Tests for resource_url_from_server_url function
814

@@ -121,3 +127,39 @@ def test_check_resource_allowed_empty_paths():
121127
assert check_resource_allowed("https://example.com", "https://example.com") is True
122128
assert check_resource_allowed("https://example.com/", "https://example.com") is True
123129
assert check_resource_allowed("https://example.com/api", "https://example.com") is True
130+
131+
132+
def test_add_query_params_appends_after_existing_params_and_keeps_fragment():
133+
"""SDK-defined: new params follow the existing query; path and fragment are untouched."""
134+
url = add_query_params("https://example.com/cb?state=abc#frag", {"code": "xyz"})
135+
assert url == "https://example.com/cb?state=abc&code=xyz#frag"
136+
137+
138+
def test_add_query_params_duplicates_existing_key_instead_of_replacing():
139+
"""SDK-defined: an existing key is kept and the new value is appended alongside it."""
140+
assert add_query_params("https://example.com/?a=1", {"a": "2"}) == "https://example.com/?a=1&a=2"
141+
142+
143+
def test_add_query_params_reencodes_existing_query():
144+
"""SDK-defined: the whole query is re-encoded, so `%20` in existing params becomes `+`."""
145+
assert add_query_params("https://example.com/?q=a%20b", {"x": "y"}) == "https://example.com/?q=a+b&x=y"
146+
147+
148+
def test_remove_query_params_drops_every_occurrence_and_keeps_order_of_the_rest():
149+
"""SDK-defined: all values of a named key are removed; other params keep their order."""
150+
url = remove_query_params("https://example.com/?a=1&b=2&a=3&c=&d=4", ["a", "d"])
151+
assert url == "https://example.com/?b=2&c="
152+
153+
154+
def test_remove_query_params_omits_question_mark_when_query_becomes_empty():
155+
"""SDK-defined: removing the only params yields a URL with no query component."""
156+
assert remove_query_params("https://example.com/p?a=1#frag", ["a"]) == "https://example.com/p#frag"
157+
158+
159+
def test_replace_query_params_overrides_given_keys_and_keeps_the_rest():
160+
"""SDK-defined: given keys replace all existing occurrences and are appended once.
161+
162+
Other params and the fragment are kept.
163+
"""
164+
url = replace_query_params("https://example.com/p?a=1&b=2&a=3#f", {"a": "x", "c": "y"})
165+
assert url == "https://example.com/p?b=2&a=x&c=y#f"

0 commit comments

Comments
 (0)