π The fast, Pythonic way to build MCP servers and clients.
Accept any issuer scoped to the Descope project (#4909)
Kevin J Gao125717dd55b9
diff --git a/docs/integrations/descope.mdx b/docs/integrations/descope.mdxindex fbe1c2b22..f6e31bb55 100644--- a/docs/integrations/descope.mdx+++ b/docs/integrations/descope.mdx@@ -46,6 +46,8 @@ Before you begin, you will need:```https://api.descope.com/v1/apps/P.../.well-known/openid-configuration```++ The project-level URL is the recommended one.</Step></Steps>diff --git a/fastmcp_slim/fastmcp/server/auth/providers/descope.py b/fastmcp_slim/fastmcp/server/auth/providers/descope.pyindex aa1255ad1..8928cb082 100644--- a/fastmcp_slim/fastmcp/server/auth/providers/descope.py+++ b/fastmcp_slim/fastmcp/server/auth/providers/descope.py@@ -8,6 +8,7 @@ for seamless MCP client authentication.from __future__ import annotationsimport asyncio+from typing import Anyfrom urllib.parse import urlparseimport httpx2@@ -76,13 +77,62 @@ async def _discover_scopes(openid_configuration_url: str) -> list[str] | None:return None+class _DescopeJWTVerifier(JWTVerifier):+ """JWT verifier that accepts every issuer form of a Descope project.++ A project mints tokens under several issuers, and which one a token carries+ depends on how it was minted rather than on the configuration URL this+ server was given:++ - project: `.../v1/apps/<project_id>`+ - MCP server: `.../v1/apps/agentic/<project_id>/<server_id>`+ - tenant (XAA): `.../v1/apps/<project_id>/<tenant_id>`++ All of them are signed with the same project keys and carry the project ID+ as their audience, so which one a token names does not narrow what it may+ access. Any issuer scoped to the configured project is therefore accepted.+ """++ def __init__(self, *, descope_base_url: str, project_id: str, **kwargs: Any):+ """Initialize the verifier.++ Args:+ descope_base_url: Descope API base URL, e.g. `https://api.descope.com`.+ project_id: Descope project ID that issuers must be scoped to.+ **kwargs: Passed through to `JWTVerifier`.+ """+ super().__init__(**kwargs)+ self.project_issuer = f"{descope_base_url}/v1/apps/{project_id}"+ self.agentic_issuer = f"{descope_base_url}/v1/apps/agentic/{project_id}"++ def _validate_issuer(self, issuer: Any) -> bool:+ if super()._validate_issuer(issuer):+ return True+ if not isinstance(issuer, str):+ return False+ # An MCP server ID extends the project's agentic path and a tenant ID+ # extends the project issuer, so exactly one segment may follow either.+ # The agentic path is checked first as the more specific of the two.+ for prefix in (self.agentic_issuer, self.project_issuer):+ if issuer.startswith(f"{prefix}/"):+ segment = issuer[len(prefix) + 1 :].strip("/")+ if segment and "/" not in segment:+ return True+ return False++class DescopeProvider(RemoteAuthProvider):"""Descope metadata provider for Dynamic Client Registration (DCR).The provider accepts either a resource-specific Descope MCP Server URL suchas `/v1/apps/agentic/P.../M.../.well-known/openid-configuration` or aproject-level inbound app URL such as- `/v1/apps/P.../.well-known/openid-configuration`.+ `/v1/apps/P.../.well-known/openid-configuration`. The project-level URL is+ the recommended configuration.++ Tokens are accepted from any issuer the project mints: the project-level+ issuer, the resource-scoped issuer of an MCP server, and the tenant-scoped+ issuer used by cross-app access (XAA).When neither `scopes_supported` nor `required_scopes` is provided, advertisedscopes are discovered lazily from the OpenID configuration. Use@@ -176,6 +226,11 @@ class DescopeProvider(RemoteAuthProvider):self.openid_configuration_url.replace(_OPENID_WK, _OAUTH_WK))+ # Tokens are accepted from any issuer scoped to this project, whichever+ # configuration URL was supplied (see _DescopeJWTVerifier). The+ # project-level issuer is the canonical one.+ project_issuer = f"{self.descope_base_url}/v1/apps/{self.project_id}"+# Advertised scopes are discovered from Descope's OpenID configuration# only when the caller supplied neither explicit advertised scopes nor# required scopes. Discovery is deferred to the first protected resource@@ -195,9 +250,11 @@ class DescopeProvider(RemoteAuthProvider):self._scopes_discovery_lock = asyncio.Lock()if token_verifier is None:- token_verifier = JWTVerifier(+ token_verifier = _DescopeJWTVerifier(+ descope_base_url=self.descope_base_url,+ project_id=self.project_id,jwks_uri=f"{self.descope_base_url}/{self.project_id}/.well-known/jwks.json",- issuer=issuer_url,+ issuer=project_issuer,algorithm="RS256",audience=self.project_id,required_scopes=parsed_required_scopes,diff --git a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py b/fastmcp_slim/fastmcp/server/auth/providers/jwt.pyindex d991b2ab6..74fb98740 100644--- a/fastmcp_slim/fastmcp/server/auth/providers/jwt.py+++ b/fastmcp_slim/fastmcp/server/auth/providers/jwt.py@@ -465,6 +465,18 @@ class JWTVerifier(TokenVerifier):response.raise_for_status()return response.json()+ def _validate_issuer(self, issuer: Any) -> bool:+ """Check a token's `iss` claim against the configured issuer(s).++ Subclasses override this to implement provider-specific rules, such as+ accepting a family of related issuers.+ """+ if isinstance(self.issuer, list):+ # self.issuer is a list - the token issuer must match one of them+ return issuer in self.issuer+ # self.issuer is a string - check for equality+ return issuer == self.issuer+def _extract_scopes(self, claims: dict[str, Any]) -> list[str]:"""Extract scopes from JWT claims. Supports both 'scope' and 'scp'@@ -540,16 +552,7 @@ class JWTVerifier(TokenVerifier):if self.issuer:iss = claims.get("iss")- # Handle different combinations of issuer types- issuer_valid = False- if isinstance(self.issuer, list):- # self.issuer is a list - check if token issuer matches any expected issuer- issuer_valid = iss in self.issuer- else:- # self.issuer is a string - check for equality- issuer_valid = iss == self.issuer-- if not issuer_valid:+ if not self._validate_issuer(iss):self.logger.warning("Bearer token rejected for client %s: issuer mismatch ""(got %r, expected %r)",diff --git a/tests/server/auth/providers/test_descope.py b/tests/server/auth/providers/test_descope.pyindex b35b2dd00..7bc934aa2 100644--- a/tests/server/auth/providers/test_descope.py+++ b/tests/server/auth/providers/test_descope.py@@ -10,8 +10,11 @@ from starlette.requests import Requestfrom fastmcp import Client, FastMCPfrom fastmcp.client.transports import StreamableHttpTransport-from fastmcp.server.auth.providers.descope import DescopeProvider-from fastmcp.server.auth.providers.jwt import JWTVerifier+from fastmcp.server.auth.providers.descope import (+ DescopeProvider,+ _DescopeJWTVerifier,+)+from fastmcp.server.auth.providers.jwt import JWTVerifier, RSAKeyPairfrom fastmcp.utilities.tests import HeadlessOAuth, run_server_asyncPROJECT_LEVEL_OPENID_CONFIGURATION = {@@ -355,14 +358,12 @@ class TestDescopeProvider:assert str(provider.descope_base_url) == "https://api.descope.com"assert isinstance(provider.token_verifier, JWTVerifier)assert (- provider.token_verifier.issuer- == "https://api.descope.com/v1/apps/agentic/P2new123/M123"+ provider.token_verifier.issuer == "https://api.descope.com/v1/apps/P2new123")def test_jwt_verifier_configured_correctly(self):"""Test that JWT verifier is configured correctly."""config_url = "https://api.descope.com/v1/apps/agentic/P2abc123/M123/.well-known/openid-configuration"- issuer_url = "https://api.descope.com/v1/apps/agentic/P2abc123/M123"provider = DescopeProvider(config_url=config_url,@@ -375,10 +376,146 @@ class TestDescopeProvider:provider.token_verifier.jwks_uri== "https://api.descope.com/P2abc123/.well-known/jwks.json")- assert provider.token_verifier.issuer == issuer_url- assert isinstance(provider.token_verifier, JWTVerifier)assert provider.token_verifier.audience == "P2abc123"+ def test_mcp_server_config_url_expects_the_project_level_issuer(self):+ """Descope mints project-level issuers even for MCP server config URLs."""+ provider = DescopeProvider(+ config_url="https://api.descope.com/v1/apps/agentic/P2abc123/M123/.well-known/openid-configuration",+ base_url="https://myserver.com",+ )++ assert isinstance(provider.token_verifier, _DescopeJWTVerifier)+ assert (+ provider.token_verifier.issuer == "https://api.descope.com/v1/apps/P2abc123"+ )+ # The MCP server URL remains the advertised authorization server.+ assert [str(server) for server in provider.authorization_servers] == [+ "https://api.descope.com/v1/apps/agentic/P2abc123/M123"+ ]++ def test_issuers_are_scoped_to_the_configured_project(self):+ """The verifier derives both issuer families from the project."""+ provider = DescopeProvider(+ config_url="https://api.descope.com/v1/apps/P2abc123/.well-known/openid-configuration",+ base_url="https://myserver.com",+ )++ assert isinstance(provider.token_verifier, _DescopeJWTVerifier)+ assert (+ provider.token_verifier.project_issuer+ == "https://api.descope.com/v1/apps/P2abc123"+ )+ assert (+ provider.token_verifier.agentic_issuer+ == "https://api.descope.com/v1/apps/agentic/P2abc123"+ )++ @pytest.mark.parametrize(+ "config_url",+ [+ "https://api.descope.com/v1/apps/P2abc123/.well-known/openid-configuration",+ "https://api.descope.com/v1/apps/agentic/P2abc123/M123/.well-known/openid-configuration",+ ],+ ids=["project-level-config", "mcp-server-config"],+ )+ @pytest.mark.parametrize(+ "token_issuer",+ [+ "https://api.descope.com/v1/apps/P2abc123",+ "https://api.descope.com/v1/apps/agentic/P2abc123/M123",+ "https://api.descope.com/v1/apps/P2abc123/T2tenant456",+ ],+ ids=["project-level-issuer", "mcp-server-issuer", "tenant-issuer"],+ )+ async def test_every_issuer_form_is_accepted(+ self, config_url: str, token_issuer: str+ ):+ """Both config URL forms accept all three issuer forms of the project."""+ key_pair = RSAKeyPair.generate()+ provider = DescopeProvider(+ config_url=config_url, base_url="https://myserver.com"+ )+ token = key_pair.create_token(+ subject="user-123",+ issuer=token_issuer,+ audience="P2abc123",+ )++ with patch.object(+ JWTVerifier,+ "_get_verification_key",+ new=AsyncMock(return_value=key_pair.public_key),+ ):+ access_token = await provider.token_verifier.verify_token(token)++ assert access_token is not None+ assert access_token.claims["iss"] == token_issuer++ async def test_old_api_accepts_every_issuer_form(self):+ """project_id + descope_base_url derive the same project-scoped issuers."""+ key_pair = RSAKeyPair.generate()+ provider = DescopeProvider(+ project_id="P2abc123",+ descope_base_url="https://api.descope.com",+ base_url="https://myserver.com",+ )+ tokens = [+ key_pair.create_token(issuer=issuer, audience="P2abc123")+ for issuer in (+ "https://api.descope.com/v1/apps/P2abc123",+ "https://api.descope.com/v1/apps/agentic/P2abc123/M123",+ "https://api.descope.com/v1/apps/P2abc123/T2tenant456",+ )+ ]++ with patch.object(+ JWTVerifier,+ "_get_verification_key",+ new=AsyncMock(return_value=key_pair.public_key),+ ):+ for token in tokens:+ assert await provider.token_verifier.verify_token(token) is not None++ @pytest.mark.parametrize(+ "token_issuer",+ [+ # Another project entirely.+ "https://api.descope.com/v1/apps/agentic/P2other456/M123",+ # Extra path segments below an MCP server.+ "https://api.descope.com/v1/apps/agentic/P2abc123/M123/extra",+ # The agentic path with no MCP server ID.+ "https://api.descope.com/v1/apps/agentic/P2abc123",+ # A different Descope deployment.+ "https://evil.example.com/v1/apps/agentic/P2abc123/M123",+ # A tenant of a different project.+ "https://api.descope.com/v1/apps/P2other456/T2tenant789",+ # A project ID that merely starts with the configured one.+ "https://api.descope.com/v1/apps/P2abc123456",+ # Another project's project-level issuer.+ "https://api.descope.com/v1/apps/P2other456",+ ],+ )+ async def test_issuers_outside_the_project_are_rejected(self, token_issuer: str):+ """Only issuers of the configured project, plus one ID segment, pass."""+ key_pair = RSAKeyPair.generate()+ provider = DescopeProvider(+ config_url="https://api.descope.com/v1/apps/P2abc123/.well-known/openid-configuration",+ base_url="https://myserver.com",+ )+ token = key_pair.create_token(+ subject="user-123",+ issuer=token_issuer,+ audience="P2abc123",+ )++ with patch.object(+ JWTVerifier,+ "_get_verification_key",+ new=AsyncMock(return_value=key_pair.public_key),+ ):+ assert await provider.token_verifier.verify_token(token) is None+def test_required_scopes_support(self):"""Test that required_scopes are supported and passed to JWT verifier."""provider = DescopeProvider(