diff --git a/src/mcp/shared/auth.py b/src/mcp/shared/auth.py index 3b48152d5b..e3418c124f 100644 --- a/src/mcp/shared/auth.py +++ b/src/mcp/shared/auth.py @@ -1,4 +1,4 @@ -from typing import Any, Literal +from typing import Any, Literal, cast from pydantic import AnyHttpUrl, AnyUrl, BaseModel, Field, field_validator @@ -85,6 +85,14 @@ def _empty_string_optional_url_to_none(cls, v: object) -> object: return None return v + @field_validator("redirect_uris", mode="before") + @classmethod + def _normalize_redirect_uris(cls, v: object) -> object: + if isinstance(v, list | tuple | set | frozenset): + redirect_uris = cast(list[Any] | tuple[Any, ...] | set[Any] | frozenset[Any], v) + return [str(uri) for uri in redirect_uris] + return v + def validate_scope(self, requested_scope: str | None) -> list[str] | None: if requested_scope is None: return None diff --git a/tests/shared/test_auth.py b/tests/shared/test_auth.py index 7463bc5a8a..68bff832d6 100644 --- a/tests/shared/test_auth.py +++ b/tests/shared/test_auth.py @@ -1,7 +1,9 @@ """Tests for OAuth 2.0 shared code.""" +from typing import Any + import pytest -from pydantic import ValidationError +from pydantic import AnyHttpUrl, AnyUrl, ValidationError from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthMetadata @@ -109,6 +111,27 @@ def test_valid_url_passes_through_unchanged(): assert str(metadata.client_uri) == "https://udemy.com/" +@pytest.mark.parametrize( + "redirect_uris", + [ + [AnyHttpUrl("https://example.com/callback")], + (AnyHttpUrl("https://example.com/callback"),), + {AnyHttpUrl("https://example.com/callback")}, + frozenset({AnyHttpUrl("https://example.com/callback")}), + ], +) +def test_redirect_uri_url_subtypes_are_normalized(redirect_uris: Any): + info = OAuthClientInformationFull( + client_id="abc123", + redirect_uris=redirect_uris, + ) + + incoming = AnyUrl("https://example.com/callback") + + assert info.validate_redirect_uri(incoming) == incoming + assert info.model_dump(mode="json")["redirect_uris"] == ["https://example.com/callback"] + + def test_information_full_inherits_coercion(): """OAuthClientInformationFull subclasses OAuthClientMetadata, so the same coercion applies to DCR responses parsed via the full model."""