Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/mcp/shared/auth_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@
from pydantic import AnyUrl, HttpUrl


def _lowercase_host(netloc: str) -> str:
userinfo, separator, hostport = netloc.rpartition("@")
prefix = f"{userinfo}{separator}" if separator else ""

if hostport.startswith("["):
end = hostport.find("]")
if end != -1:
return f"{prefix}{hostport[: end + 1].lower()}{hostport[end + 1 :]}"

host, separator, port = hostport.partition(":")
return f"{prefix}{host.lower()}{separator}{port}"


def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:
"""Convert server URL to canonical resource URL per RFC 8707.

Expand All @@ -23,7 +36,13 @@ def resource_url_from_server_url(url: str | HttpUrl | AnyUrl) -> str:

# Parse the URL and remove fragment, create canonical form
parsed = urlsplit(url_str)
canonical = urlunsplit(parsed._replace(scheme=parsed.scheme.lower(), netloc=parsed.netloc.lower(), fragment=""))
canonical = urlunsplit(
parsed._replace(
scheme=parsed.scheme.lower(),
netloc=_lowercase_host(parsed.netloc),
fragment="",
)
)

return canonical

Expand Down
8 changes: 8 additions & 0 deletions tests/shared/test_auth_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@ def test_resource_url_from_server_url_lowercase_scheme_and_host():
assert resource_url_from_server_url("Http://Example.Com:8080/") == "http://example.com:8080/"


def test_resource_url_from_server_url_preserves_userinfo_case():
"""Only the scheme and host are canonicalized; userinfo is preserved byte-for-byte."""
assert (
resource_url_from_server_url("HTTPS://User:PaSs@EXAMPLE.COM/path#fragment")
== "https://User:PaSs@example.com/path"
)


def test_resource_url_from_server_url_handles_pydantic_urls():
"""Should handle Pydantic URL types."""
url = HttpUrl("https://example.com/path")
Expand Down
Loading