Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

refactor: move scope parser to utilities (#1642)

Jeremiah Lowinaef6d23fb96f
diff --git a/docs/integrations/azure.mdx b/docs/integrations/azure.mdx
index ad8fc31a9..890e648e3 100644
--- a/docs/integrations/azure.mdx
+++ b/docs/integrations/azure.mdx
@@ -212,7 +212,7 @@ Redirect path configured in your Azure App registration
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES" default='["User.Read", "email", "openid", "profile"]'>
-Comma-separated list of required Microsoft Graph scopes
+Comma-, space-, or JSON-separated list of required Microsoft Graph scopes
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_AZURE_TIMEOUT_SECONDS" default="10">
diff --git a/docs/integrations/github.mdx b/docs/integrations/github.mdx
index b849e1bd4..0d05126f7 100644
--- a/docs/integrations/github.mdx
+++ b/docs/integrations/github.mdx
@@ -169,7 +169,7 @@ Redirect path configured in your GitHub OAuth App
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_REQUIRED_SCOPES" default='["user"]'>
-Comma-separated list of required GitHub scopes (e.g., `user,repo`)
+Comma-, space-, or JSON-separated list of required GitHub scopes (e.g., `user repo` or `["user","repo"]`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GITHUB_TIMEOUT_SECONDS" default="10">
diff --git a/docs/integrations/google.mdx b/docs/integrations/google.mdx
index 14a79a80c..c3ff3cc7b 100644
--- a/docs/integrations/google.mdx
+++ b/docs/integrations/google.mdx
@@ -179,7 +179,7 @@ Redirect path configured in your Google OAuth Client
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_REQUIRED_SCOPES" default="[]">
-Comma-separated list of required Google scopes (e.g., `openid`)
+Comma-, space-, or JSON-separated list of required Google scopes (e.g., `openid,profile` or `["openid","profile"]`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_GOOGLE_TIMEOUT_SECONDS" default="10">
diff --git a/docs/integrations/workos-oauth.mdx b/docs/integrations/workos-oauth.mdx
index 34e9198f4..fee2b1c46 100644
--- a/docs/integrations/workos-oauth.mdx
+++ b/docs/integrations/workos-oauth.mdx
@@ -166,7 +166,7 @@ Redirect path configured in your WorkOS OAuth App
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_WORKOS_REQUIRED_SCOPES" default="[]">
-List of required OAuth scopes (e.g., `["openid", "profile", "email"]`)
+Comma-, space-, or JSON-separated list of required OAuth scopes (e.g., `openid profile email` or `["openid","profile","email"]`)
</ParamField>
<ParamField path="FASTMCP_SERVER_AUTH_WORKOS_TIMEOUT_SECONDS" default="10">
diff --git a/src/fastmcp/server/auth/providers/azure.py b/src/fastmcp/server/auth/providers/azure.py
index 2bb0b924c..a4de21021 100644
--- a/src/fastmcp/server/auth/providers/azure.py
+++ b/src/fastmcp/server/auth/providers/azure.py
@@ -7,12 +7,13 @@ using the OAuth Proxy pattern for non-DCR OAuth flows.
from __future__ import annotations
import httpx
-from pydantic import SecretStr
+from pydantic import SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from fastmcp.server.auth import AccessToken, TokenVerifier
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.registry import register_provider
+from fastmcp.utilities.auth import parse_scopes
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import NotSet, NotSetT
@@ -36,6 +37,11 @@ class AzureProviderSettings(BaseSettings):
required_scopes: list[str] | None = None
timeout_seconds: int | None = None
+ @field_validator("required_scopes", mode="before")
+ @classmethod
+ def _parse_scopes(cls, v):
+ return parse_scopes(v)
+
class AzureTokenVerifier(TokenVerifier):
"""Token verifier for Azure OAuth tokens.
diff --git a/src/fastmcp/server/auth/providers/github.py b/src/fastmcp/server/auth/providers/github.py
index cddf83fdf..4f3fcc862 100644
--- a/src/fastmcp/server/auth/providers/github.py
+++ b/src/fastmcp/server/auth/providers/github.py
@@ -22,13 +22,14 @@ Example:
from __future__ import annotations
import httpx
-from pydantic import AnyHttpUrl, SecretStr
+from pydantic import AnyHttpUrl, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from fastmcp.server.auth import TokenVerifier
from fastmcp.server.auth.auth import AccessToken
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.registry import register_provider
+from fastmcp.utilities.auth import parse_scopes
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import NotSet, NotSetT
@@ -51,6 +52,11 @@ class GitHubProviderSettings(BaseSettings):
required_scopes: list[str] | None = None
timeout_seconds: int | None = None
+ @field_validator("required_scopes", mode="before")
+ @classmethod
+ def _parse_scopes(cls, v):
+ return parse_scopes(v)
+
class GitHubTokenVerifier(TokenVerifier):
"""Token verifier for GitHub OAuth tokens.
diff --git a/src/fastmcp/server/auth/providers/google.py b/src/fastmcp/server/auth/providers/google.py
index 48f61bf8a..920034395 100644
--- a/src/fastmcp/server/auth/providers/google.py
+++ b/src/fastmcp/server/auth/providers/google.py
@@ -24,13 +24,14 @@ from __future__ import annotations
import time
import httpx
-from pydantic import AnyHttpUrl, SecretStr
+from pydantic import AnyHttpUrl, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from fastmcp.server.auth import TokenVerifier
from fastmcp.server.auth.auth import AccessToken
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.registry import register_provider
+from fastmcp.utilities.auth import parse_scopes
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import NotSet, NotSetT
@@ -53,6 +54,11 @@ class GoogleProviderSettings(BaseSettings):
required_scopes: list[str] | None = None
timeout_seconds: int | None = None
+ @field_validator("required_scopes", mode="before")
+ @classmethod
+ def _parse_scopes(cls, v):
+ return parse_scopes(v)
+
class GoogleTokenVerifier(TokenVerifier):
"""Token verifier for Google OAuth tokens.
diff --git a/src/fastmcp/server/auth/providers/jwt.py b/src/fastmcp/server/auth/providers/jwt.py
index dee1bb478..19eac1bb2 100644
--- a/src/fastmcp/server/auth/providers/jwt.py
+++ b/src/fastmcp/server/auth/providers/jwt.py
@@ -11,12 +11,13 @@ from authlib.jose import JsonWebKey, JsonWebToken
from authlib.jose.errors import JoseError
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
-from pydantic import AnyHttpUrl, SecretStr
+from pydantic import AnyHttpUrl, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from typing_extensions import TypedDict
from fastmcp.server.auth import AccessToken, TokenVerifier
from fastmcp.server.auth.registry import register_provider
+from fastmcp.utilities.auth import parse_scopes
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import NotSet, NotSetT
@@ -155,6 +156,11 @@ class JWTVerifierSettings(BaseSettings):
required_scopes: list[str] | None = None
resource_server_url: AnyHttpUrl | str | None = None
+ @field_validator("required_scopes", mode="before")
+ @classmethod
+ def _parse_scopes(cls, v):
+ return parse_scopes(v)
+
@register_provider("JWT")
class JWTVerifier(TokenVerifier):
diff --git a/src/fastmcp/server/auth/providers/workos.py b/src/fastmcp/server/auth/providers/workos.py
index a1d77fd08..2fc138141 100644
--- a/src/fastmcp/server/auth/providers/workos.py
+++ b/src/fastmcp/server/auth/providers/workos.py
@@ -11,7 +11,7 @@ Choose based on your WorkOS setup and authentication requirements.
from __future__ import annotations
import httpx
-from pydantic import AnyHttpUrl, SecretStr
+from pydantic import AnyHttpUrl, SecretStr, field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from starlette.responses import JSONResponse
from starlette.routing import Route
@@ -20,6 +20,7 @@ from fastmcp.server.auth import AccessToken, RemoteAuthProvider, TokenVerifier
from fastmcp.server.auth.oauth_proxy import OAuthProxy
from fastmcp.server.auth.providers.jwt import JWTVerifier
from fastmcp.server.auth.registry import register_provider
+from fastmcp.utilities.auth import parse_scopes
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.types import NotSet, NotSetT
@@ -43,6 +44,11 @@ class WorkOSProviderSettings(BaseSettings):
required_scopes: list[str] | None = None
timeout_seconds: int | None = None
+ @field_validator("required_scopes", mode="before")
+ @classmethod
+ def _parse_scopes(cls, v):
+ return parse_scopes(v)
+
class WorkOSTokenVerifier(TokenVerifier):
"""Token verifier for WorkOS OAuth tokens.
@@ -255,6 +261,11 @@ class AuthKitProviderSettings(BaseSettings):
base_url: AnyHttpUrl
required_scopes: list[str] | None = None
+ @field_validator("required_scopes", mode="before")
+ @classmethod
+ def _parse_scopes(cls, v):
+ return parse_scopes(v)
+
@register_provider("AUTHKIT")
class AuthKitProvider(RemoteAuthProvider):
diff --git a/src/fastmcp/utilities/auth.py b/src/fastmcp/utilities/auth.py
new file mode 100644
index 000000000..bec370ac7
--- /dev/null
+++ b/src/fastmcp/utilities/auth.py
@@ -0,0 +1,34 @@
+"""Authentication utility helpers."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+
+def parse_scopes(value: Any) -> list[str] | None:
+ """Parse scopes from environment variables or settings values.
+
+ Accepts either a JSON array string, a comma- or space-separated string,
+ a list of strings, or ``None``. Returns a list of scopes or ``None`` if
+ no value is provided.
+ """
+ if value is None or value == "":
+ return None if value is None else []
+ if isinstance(value, list):
+ return [str(v).strip() for v in value if str(v).strip()]
+ if isinstance(value, str):
+ value = value.strip()
+ if not value:
+ return []
+ # Try JSON array first
+ if value.startswith("["):
+ try:
+ data = json.loads(value)
+ if isinstance(data, list):
+ return [str(v).strip() for v in data if str(v).strip()]
+ except Exception:
+ pass
+ # Fallback to comma/space separated list
+ return [s.strip() for s in value.replace(",", " ").split() if s.strip()]
+ return value
diff --git a/tests/server/auth/providers/test_azure.py b/tests/server/auth/providers/test_azure.py
index b47c0e837..7f76502be 100644
--- a/tests/server/auth/providers/test_azure.py
+++ b/tests/server/auth/providers/test_azure.py
@@ -31,7 +31,14 @@ class TestAzureProvider:
parsed_token = urlparse(provider._upstream_token_endpoint)
assert "87654321-4321-4321-4321-210987654321" in parsed_token.path
- def test_init_with_env_vars(self):
+ @pytest.mark.parametrize(
+ "scopes_env",
+ [
+ "User.Read,Calendar.Read",
+ '["User.Read", "Calendar.Read"]',
+ ],
+ )
+ def test_init_with_env_vars(self, scopes_env):
"""Test AzureProvider initialization from environment variables."""
with patch.dict(
os.environ,
@@ -40,7 +47,7 @@ class TestAzureProvider:
"FASTMCP_SERVER_AUTH_AZURE_CLIENT_SECRET": "env-secret",
"FASTMCP_SERVER_AUTH_AZURE_TENANT_ID": "env-tenant-id",
"FASTMCP_SERVER_AUTH_AZURE_BASE_URL": "https://envserver.com",
- "FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES": '["User.Read", "Calendar.Read"]',
+ "FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES": scopes_env,
},
):
provider = AzureProvider()
@@ -48,6 +55,10 @@ class TestAzureProvider:
assert provider._upstream_client_id == "env-client-id"
assert provider._upstream_client_secret.get_secret_value() == "env-secret"
assert str(provider.base_url) == "https://envserver.com/"
+ assert provider._token_validator.required_scopes == [
+ "User.Read",
+ "Calendar.Read",
+ ]
# Check tenant is in the endpoints
parsed_auth = urlparse(provider._upstream_authorization_endpoint)
assert "env-tenant-id" in parsed_auth.path
diff --git a/tests/server/auth/providers/test_github.py b/tests/server/auth/providers/test_github.py
index 7c3725f31..198105774 100644
--- a/tests/server/auth/providers/test_github.py
+++ b/tests/server/auth/providers/test_github.py
@@ -83,7 +83,14 @@ class TestGitHubProvider:
) # URLs get normalized with trailing slash
assert provider._redirect_path == "/custom/callback"
- def test_init_with_env_vars(self):
+ @pytest.mark.parametrize(
+ "scopes_env",
+ [
+ "user,repo",
+ '["user", "repo"]',
+ ],
+ )
+ def test_init_with_env_vars(self, scopes_env):
"""Test initialization with environment variables."""
with patch.dict(
os.environ,
@@ -91,6 +98,7 @@ class TestGitHubProvider:
"FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID": "env_client_id",
"FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET": "env_secret",
"FASTMCP_SERVER_AUTH_GITHUB_BASE_URL": "https://env-example.com",
+ "FASTMCP_SERVER_AUTH_GITHUB_REQUIRED_SCOPES": scopes_env,
},
):
provider = GitHubProvider()
@@ -98,6 +106,7 @@ class TestGitHubProvider:
assert provider._upstream_client_id == "env_client_id"
assert provider._upstream_client_secret.get_secret_value() == "env_secret"
assert str(provider.base_url) == "https://env-example.com/"
+ assert provider._token_validator.required_scopes == ["user", "repo"]
def test_init_explicit_overrides_env(self):
"""Test that explicit parameters override environment variables."""
diff --git a/tests/server/auth/providers/test_google.py b/tests/server/auth/providers/test_google.py
index 3f68eb152..4402e16fd 100644
--- a/tests/server/auth/providers/test_google.py
+++ b/tests/server/auth/providers/test_google.py
@@ -24,7 +24,14 @@ class TestGoogleProvider:
assert provider._upstream_client_secret.get_secret_value() == "GOCSPX-test123"
assert str(provider.base_url) == "https://myserver.com/"
- def test_init_with_env_vars(self):
+ @pytest.mark.parametrize(
+ "scopes_env",
+ [
+ "openid,https://www.googleapis.com/auth/userinfo.email",
+ '["openid", "https://www.googleapis.com/auth/userinfo.email"]',
+ ],
+ )
+ def test_init_with_env_vars(self, scopes_env):
"""Test GoogleProvider initialization from environment variables."""
with patch.dict(
os.environ,
@@ -32,7 +39,7 @@ class TestGoogleProvider:
"FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_ID": "env123.apps.googleusercontent.com",
"FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRET": "GOCSPX-env456",
"FASTMCP_SERVER_AUTH_GOOGLE_BASE_URL": "https://envserver.com",
- "FASTMCP_SERVER_AUTH_GOOGLE_REQUIRED_SCOPES": '["openid", "https://www.googleapis.com/auth/userinfo.email"]',
+ "FASTMCP_SERVER_AUTH_GOOGLE_REQUIRED_SCOPES": scopes_env,
},
):
provider = GoogleProvider()
@@ -42,6 +49,10 @@ class TestGoogleProvider:
provider._upstream_client_secret.get_secret_value() == "GOCSPX-env456"
)
assert str(provider.base_url) == "https://envserver.com/"
+ assert provider._token_validator.required_scopes == [
+ "openid",
+ "https://www.googleapis.com/auth/userinfo.email",
+ ]
def test_init_missing_client_id_raises_error(self):
"""Test that missing client_id raises ValueError."""
diff --git a/tests/server/auth/providers/test_workos.py b/tests/server/auth/providers/test_workos.py
index 8f2643bef..38e23239d 100644
--- a/tests/server/auth/providers/test_workos.py
+++ b/tests/server/auth/providers/test_workos.py
@@ -26,7 +26,14 @@ class TestWorkOSProvider:
assert provider._upstream_client_secret.get_secret_value() == "secret_test456"
assert str(provider.base_url) == "https://myserver.com/"
- def test_init_with_env_vars(self):
+ @pytest.mark.parametrize(
+ "scopes_env",
+ [
+ "openid,email",
+ '["openid", "email"]',
+ ],
+ )
+ def test_init_with_env_vars(self, scopes_env):
"""Test WorkOSProvider initialization from environment variables."""
with patch.dict(
os.environ,
@@ -35,7 +42,7 @@ class TestWorkOSProvider:
"FASTMCP_SERVER_AUTH_WORKOS_CLIENT_SECRET": "env_secret",
"FASTMCP_SERVER_AUTH_WORKOS_AUTHKIT_DOMAIN": "https://env.authkit.app",
"FASTMCP_SERVER_AUTH_WORKOS_BASE_URL": "https://envserver.com",
- "FASTMCP_SERVER_AUTH_WORKOS_REQUIRED_SCOPES": '["openid", "email"]',
+ "FASTMCP_SERVER_AUTH_WORKOS_REQUIRED_SCOPES": scopes_env,
},
):
provider = WorkOSProvider()
@@ -43,6 +50,10 @@ class TestWorkOSProvider:
assert provider._upstream_client_id == "env_client"
assert provider._upstream_client_secret.get_secret_value() == "env_secret"
assert str(provider.base_url) == "https://envserver.com/"
+ assert provider._token_validator.required_scopes == [
+ "openid",
+ "email",
+ ]
def test_init_missing_client_id_raises_error(self):
"""Test that missing client_id raises ValueError."""