Skip to content

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

Fix Azure scope mismatch causing MCP client validation errors (#2243)

Jeremiah Lowina1a5cca76569
diff --git a/src/fastmcp/server/auth/providers/azure.py b/src/fastmcp/server/auth/providers/azure.py
index dcb070bee..387b4f15f 100644
--- a/src/fastmcp/server/auth/providers/azure.py
+++ b/src/fastmcp/server/auth/providers/azure.py
@@ -64,18 +64,28 @@ class AzureProvider(OAuthProxy):
OAuth Proxy pattern. It supports both organizational accounts and personal
Microsoft accounts depending on the tenant configuration.
+ Scope Handling:
+ - required_scopes: Provide unprefixed scope names (e.g., ["read", "write"])
+ β†’ Automatically prefixed with identifier_uri during initialization
+ β†’ Validated on all tokens and advertised to MCP clients
+ - additional_authorize_scopes: Provide full format (e.g., ["User.Read"])
+ β†’ NOT prefixed, NOT validated, NOT advertised to clients
+ β†’ Used to request Microsoft Graph or other upstream API permissions
+
Features:
- OAuth proxy to Azure/Microsoft identity platform
- JWT validation using tenant issuer and JWKS
- Supports tenant configurations: specific tenant ID, "organizations", or "consumers"
+ - Custom API scopes and Microsoft Graph scopes in a single provider
Setup:
1. Create an App registration in Azure Portal
2. Configure Web platform redirect URI: http://localhost:8000/auth/callback (or your custom path)
- 3. Add an Application ID URI. Either use the default (api://{client_id}) or set a custom one.
- 4. Add a custom scope.
- 5. Create a client secret.
- 6. Get Application (client) ID, Directory (tenant) ID, and client secret
+ 3. Add an Application ID URI under "Expose an API" (defaults to api://{client_id})
+ 4. Add custom scopes (e.g., "read", "write") under "Expose an API"
+ 5. Set access token version to 2 in the App manifest: "requestedAccessTokenVersion": 2
+ 6. Create a client secret
+ 7. Get Application (client) ID, Directory (tenant) ID, and client secret
Example:
```python
@@ -86,7 +96,8 @@ class AzureProvider(OAuthProxy):
client_id="your-client-id",
client_secret="your-client-secret",
tenant_id="your-tenant-id",
- required_scopes=["your-scope"],
+ required_scopes=["read", "write"], # Unprefixed scope names
+ additional_authorize_scopes=["User.Read", "Mail.Read"], # Optional Graph scopes
base_url="http://localhost:8000",
# identifier_uri defaults to api://{client_id}
)
@@ -116,21 +127,31 @@ class AzureProvider(OAuthProxy):
"""Initialize Azure OAuth provider.
Args:
- client_id: Azure application (client) ID
- client_secret: Azure client secret
- tenant_id: Azure tenant ID (your specific tenant ID, "organizations", or "consumers")
- identifier_uri: Optional Application ID URI for your API. (defaults to api://{client_id})
- Used only to prefix scopes in authorization requests. Tokens are always validated
- against your app's client ID.
+ client_id: Azure application (client) ID from your App registration
+ client_secret: Azure client secret from your App registration
+ tenant_id: Azure tenant ID (specific tenant GUID, "organizations", or "consumers")
+ identifier_uri: Optional Application ID URI for your custom API (defaults to api://{client_id}).
+ This URI is automatically prefixed to all required_scopes during initialization.
+ Example: identifier_uri="api://my-api" + required_scopes=["read"]
+ β†’ tokens validated for "api://my-api/read"
base_url: Public URL where OAuth endpoints will be accessible (includes any mount path)
issuer_url: Issuer URL for OAuth metadata (defaults to base_url). Use root-level URL
to avoid 404s during discovery when mounting under a path.
- redirect_path: Redirect path configured in Azure (defaults to "/auth/callback")
- required_scopes: Required scopes. These are validated on tokens and used as defaults
- when the client does not request specific scopes.
- additional_authorize_scopes: Additional scopes to include in the authorization request
- without prefixing. Use this to request upstream scopes such as Microsoft Graph
- permissions. These are not used for token validation.
+ redirect_path: Redirect path configured in Azure App registration (defaults to "/auth/callback")
+ required_scopes: Custom API scope names WITHOUT prefix (e.g., ["read", "write"]).
+ - Automatically prefixed with identifier_uri during initialization
+ - Validated on all tokens
+ - Advertised in Protected Resource Metadata
+ - Must match scope names defined in Azure Portal under "Expose an API"
+ Example: ["read", "write"] β†’ validates tokens containing ["api://xxx/read", "api://xxx/write"]
+ additional_authorize_scopes: Microsoft Graph or other upstream scopes in full format.
+ - NOT prefixed with identifier_uri
+ - NOT validated on tokens
+ - NOT advertised to MCP clients
+ - Used to request additional permissions from Azure (e.g., Graph API access)
+ Example: ["User.Read", "Mail.Read", "offline_access"]
+ These scopes allow your FastMCP server to call Microsoft Graph APIs using the
+ upstream Azure token, but MCP clients are unaware of them.
allowed_client_redirect_uris: List of allowed redirect URI patterns for MCP clients.
If None (default), all URIs are allowed. If empty list, no URIs are allowed.
client_storage: An AsyncKeyValue-compatible store for client registrations, registrations are stored in memory if not provided
@@ -189,6 +210,12 @@ class AzureProvider(OAuthProxy):
self.additional_authorize_scopes = settings.additional_authorize_scopes or []
tenant_id_final = settings.tenant_id
+ # Prefix required scopes with identifier_uri for Azure
+ # Azure returns scopes as full URIs (e.g., "api://xxx/read") in tokens
+ prefixed_required_scopes = [
+ f"{self.identifier_uri}/{scope}" for scope in settings.required_scopes
+ ]
+
# Always validate tokens against the app's API client ID using JWT
issuer = f"https://login.microsoftonline.com/{tenant_id_final}/v2.0"
jwks_uri = (
@@ -200,7 +227,7 @@ class AzureProvider(OAuthProxy):
issuer=issuer,
audience=settings.client_id,
algorithm="RS256",
- required_scopes=settings.required_scopes,
+ required_scopes=prefixed_required_scopes,
)
# Extract secret string from SecretStr
@@ -272,14 +299,14 @@ class AzureProvider(OAuthProxy):
"Filtering out 'resource' parameter '%s' for Azure AD v2.0 (use scopes instead)",
original_resource,
)
- original_scopes = params_to_use.scopes or self.required_scopes
- prefixed_scopes = (
- self._add_prefix_to_scopes(original_scopes)
- if self.identifier_uri
- else original_scopes
- )
-
- final_scopes = list(prefixed_scopes)
+ # Scopes are already prefixed:
+ # - self.required_scopes was prefixed during __init__
+ # - Client scopes come from PRM which advertises prefixed scopes
+ scopes = params_to_use.scopes or self.required_scopes
+
+ final_scopes = list(scopes)
+ # Add Microsoft Graph scopes separately - these use shorthand format (e.g., "User.Read")
+ # and should not be prefixed with identifier_uri. Azure returns them as-is in tokens.
if self.additional_authorize_scopes:
final_scopes.extend(self.additional_authorize_scopes)
@@ -288,7 +315,3 @@ class AzureProvider(OAuthProxy):
auth_url = await super().authorize(client, modified_params)
separator = "&" if "?" in auth_url else "?"
return f"{auth_url}{separator}prompt=select_account"
-
- def _add_prefix_to_scopes(self, scopes: list[str]) -> list[str]:
- """Add Application ID URI prefix for authorization request."""
- return [f"{self.identifier_uri}/{scope}" for scope in scopes]
diff --git a/tests/server/auth/providers/test_azure.py b/tests/server/auth/providers/test_azure.py
index 970a5c3b3..5826ba33c 100644
--- a/tests/server/auth/providers/test_azure.py
+++ b/tests/server/auth/providers/test_azure.py
@@ -23,7 +23,7 @@ class TestAzureProvider:
client_secret="azure_secret_123",
tenant_id="87654321-4321-4321-4321-210987654321",
base_url="https://myserver.com",
- required_scopes=["User.Read", "Mail.Read"],
+ required_scopes=["read", "write"],
)
assert provider._upstream_client_id == "12345678-1234-1234-1234-123456789012"
@@ -38,8 +38,8 @@ class TestAzureProvider:
@pytest.mark.parametrize(
"scopes_env",
[
- "User.Read,Calendar.Read",
- '["User.Read", "Calendar.Read"]',
+ "read,write",
+ '["read", "write"]',
],
)
def test_init_with_env_vars(self, scopes_env):
@@ -59,9 +59,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/"
+ # Scopes should be prefixed with identifier_uri in token validator
assert provider._token_validator.required_scopes == [
- "User.Read",
- "Calendar.Read",
+ "api://env-client-id/read",
+ "api://env-client-id/write",
]
# Check tenant is in the endpoints
parsed_auth = urlparse(provider._upstream_authorization_endpoint)
@@ -99,7 +100,7 @@ class TestAzureProvider:
client_id="test_client",
client_secret="test_secret",
tenant_id="test-tenant",
- required_scopes=["User.Read"],
+ required_scopes=["read"],
)
# Check defaults
@@ -114,7 +115,7 @@ class TestAzureProvider:
client_secret="test_secret",
tenant_id="my-tenant-id",
base_url="https://myserver.com",
- required_scopes=["User.Read"],
+ required_scopes=["read"],
)
# Check that endpoints use the correct Azure OAuth2 v2.0 endpoints with tenant
@@ -137,7 +138,7 @@ class TestAzureProvider:
client_id="test_client",
client_secret="test_secret",
tenant_id="organizations",
- required_scopes=["User.Read"],
+ required_scopes=["read"],
)
parsed = urlparse(provider1._upstream_authorization_endpoint)
assert "/organizations/" in parsed.path
@@ -147,29 +148,33 @@ class TestAzureProvider:
client_id="test_client",
client_secret="test_secret",
tenant_id="consumers",
- required_scopes=["User.Read"],
+ required_scopes=["read"],
)
parsed = urlparse(provider2._upstream_authorization_endpoint)
assert "/consumers/" in parsed.path
def test_azure_specific_scopes(self):
- """Test handling of Azure-specific scope formats."""
- # Just test that the provider accepts Azure-specific scopes without error
+ """Test handling of custom API scope formats."""
+ # Test that the provider accepts custom API scopes without error
provider = AzureProvider(
client_id="test_client",
client_secret="test_secret",
tenant_id="test-tenant",
required_scopes=[
- "User.Read",
- "Mail.Read",
- "Calendar.ReadWrite",
- "openid",
- "profile",
+ "read",
+ "write",
+ "admin",
],
)
# Provider should initialize successfully with these scopes
assert provider is not None
+ # Scopes should be prefixed in token validator
+ assert provider._token_validator.required_scopes == [
+ "api://test_client/read",
+ "api://test_client/write",
+ "api://test_client/admin",
+ ]
def test_init_does_not_require_api_client_id_anymore(self):
"""API client ID is no longer required; audience is client_id."""
@@ -177,7 +182,7 @@ class TestAzureProvider:
client_id="test_client",
client_secret="test_secret",
tenant_id="test-tenant",
- required_scopes=["User.Read"],
+ required_scopes=["read"],
)
assert provider is not None
@@ -200,10 +205,12 @@ class TestAzureProvider:
)
assert verifier.issuer == "https://login.microsoftonline.com/my-tenant/v2.0"
assert verifier.audience == "test_client"
+ # Scopes should be prefixed with identifier_uri
+ assert verifier.required_scopes == ["api://my-api/.default"]
@pytest.mark.asyncio
- async def test_authorize_filters_resource_and_prefixes_scopes_with_audience(self):
- """authorize() should drop resource and prefix non-openid scopes with audience."""
+ async def test_authorize_filters_resource_and_accepts_prefixed_scopes(self):
+ """authorize() should drop resource parameter and accept prefixed scopes from clients."""
provider = AzureProvider(
client_id="test_client",
client_secret="test_secret",
@@ -230,7 +237,10 @@ class TestAzureProvider:
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
- scopes=["read", "profile"],
+ scopes=[
+ "api://my-api/read",
+ "api://my-api/profile",
+ ], # Client sends prefixed scopes from PRM
state="abc",
code_challenge="xyz",
resource="https://should.be.ignored",
@@ -253,8 +263,8 @@ class TestAzureProvider:
assert transaction.resource is None
@pytest.mark.asyncio
- async def test_authorize_appends_unprefixed_additional_scopes(self):
- """authorize() should append additional_authorize_scopes without prefixing them."""
+ async def test_authorize_appends_additional_scopes(self):
+ """authorize() should append additional_authorize_scopes to the authorization request."""
provider = AzureProvider(
client_id="test_client",
client_secret="test_secret",
@@ -282,7 +292,7 @@ class TestAzureProvider:
params = AuthorizationParams(
redirect_uri=AnyUrl("http://localhost:12345/callback"),
redirect_uri_provided_explicitly=True,
- scopes=["read"],
+ scopes=["api://my-api/read"], # Client sends prefixed scopes from PRM
state="abc",
code_challenge="xyz",
)