🚀 The fast, Pythonic way to build MCP servers and clients.
feat: Add support for Descope Authentication (#1853)
Anvi Banga59e250a98e6c
diff --git a/docs/docs.json b/docs/docs.jsonindex a47589616..306e771e7 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -159,6 +159,7 @@"integrations/auth0","integrations/authkit","integrations/azure",+ "integrations/descope","integrations/github","integrations/google","integrations/workos"diff --git a/docs/integrations/descope.mdx b/docs/integrations/descope.mdxnew file mode 100644index 000000000..cd6be9539--- /dev/null+++ b/docs/integrations/descope.mdx@@ -0,0 +1,155 @@+---+title: Descope 🤝 FastMCP+sidebarTitle: Descope+description: Secure your FastMCP server with Descope+icon: globe+tag: NEW+---++import { VersionBadge } from "/snippets/version-badge.mdx"++<VersionBadge version="2.12.1" />++This guide shows you how to secure your FastMCP server using [**Descope**](https://www.descope.com), a complete authentication and user management solution. This integration uses the [**Remote OAuth**](/servers/auth/remote-oauth) pattern, where Descope handles user login and your FastMCP server validates the tokens.++## Configuration++### Prerequisites++Before you begin, you will need:+1. To [sign up](https://www.descope.com/sign-up) for a Free Forever Descope account+2. Your **Project ID** from the [Descope Console](https://app.descope.com/settings/project)+3. Your FastMCP server's URL (can be localhost for development, e.g., `http://localhost:3000`)++### Step 1: Configure Descope++<Steps>+<Step title="Enable Dynamic Client Registration">+ 1. Go to the [Inbound Apps page](https://app.descope.com/apps/inbound) of the Descope Console+ 2. Click **DCR Settings**+ 3. Enable **Dynamic Client Registration (DCR)**+ 4. Define allowed scopes++ <Warning>+ DCR is required for FastMCP clients to automatically register with your authentication server.+ </Warning>+</Step>++<Step title="Note Your Project ID">+ Save your Project ID from [Project Settings](https://app.descope.com/settings/project):+ ```+ Project ID: P2abc...123+ ```+</Step>+</Steps>++### Step 2: Environment Setup++Create a `.env` file with your Descope configuration:++```bash+DESCOPE_PROJECT_ID=P2abc...123 # Your Descope Project ID+DESCOPE_BASE_URL=https://api.descope.com # Descope API URL+SERVER_URL=http://localhost:3000 # Your server's base URL+```++<Note>+You can find your project's Descope Base URL in the [Multi-Region Support Guide](https://docs.descope.com/management/project-settings/multi-regional).+</Note>++### Step 3: FastMCP Configuration++Create your FastMCP server file and use the DescopeProvider to handle all the OAuth integration automatically:++```python server.py+from fastmcp import FastMCP+from fastmcp.server.auth.providers.descope import DescopeProvider++# The DescopeProvider automatically discovers Descope endpoints+# and configures JWT token validation+auth_provider = DescopeProvider(+ project_id=DESCOPE_PROJECT_ID, # Your Descope Project ID+ base_url=SERVER_URL, # Your server's public URL+ descope_base_url=DESCOPE_BASE_URL, # Descope API base URL+)++# Create FastMCP server with auth+mcp = FastMCP(name="My Descope Protected Server", auth=auth_provider)++```++## Testing++To test your server, you can use the `fastmcp` CLI to run it locally. Assuming you've saved the above code to `server.py` (after replacing the `project_id`, `base_url`, and `descope_base_url` with your actual values!), you can run the following command:++```bash+fastmcp run server.py --transport http --port 8000+```++Now, you can use a FastMCP client to test that you can reach your server after authenticating:++```python+from fastmcp import Client+import asyncio++async def main():+ async with Client("http://localhost:8000/mcp/", auth="oauth") as client:+ assert await client.ping()++if __name__ == "__main__":+ asyncio.run(main())+```++## Environment Variables++<VersionBadge version="2.12.1" />++For production deployments, use environment variables instead of hardcoding credentials.++### Provider Selection++Setting this environment variable allows the Descope provider to be used automatically without explicitly instantiating it in code.++<Card>+<ParamField path="FASTMCP_SERVER_AUTH" default="Not set">+Set to `fastmcp.server.auth.providers.descope.DescopeProvider` to use Descope authentication.+</ParamField>+</Card>++### Descope-Specific Configuration++These environment variables provide default values for the Descope provider, whether it's instantiated manually or configured via `FASTMCP_SERVER_AUTH`.++<Card>+<ParamField path="FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_PROJECT_ID" required>+Your Descope Project ID from the [Descope Console](https://app.descope.com/settings/project)+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_BASE_URL" required>+Public URL of your FastMCP server (e.g., `https://your-server.com` or `http://localhost:8000` for development)+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_DESCOPE_BASE_URL" default="https://api.descope.com">+Descope API base URL for your [region/environment](https://docs.descope.com/management/project-settings/multi-regional)+</ParamField>+</Card>++Example `.env` file:+```bash+# Use the Descope provider+FASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.descope.DescopeProvider++# Descope configuration+FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_PROJECT_ID=P2abc...123+FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_BASE_URL=https://your-server.com+FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_DESCOPE_BASE_URL=https://api.descope.com+```++With environment variables set, your server code simplifies to:++```python server.py+from fastmcp import FastMCP++# Authentication is automatically configured from environment+mcp = FastMCP(name="My Descope Protected Server")+```\ No newline at end of filediff --git a/docs/servers/auth/authentication.mdx b/docs/servers/auth/authentication.mdxindex 9c75a776c..77526903f 100644--- a/docs/servers/auth/authentication.mdx+++ b/docs/servers/auth/authentication.mdx@@ -97,7 +97,7 @@ This example configures token validation against a JWT issuer. The `JWTVerifier`### RemoteAuthProvider-`RemoteAuthProvider` enables authentication with identity providers that **support Dynamic Client Registration (DCR)**, such as WorkOS AuthKit. With DCR, MCP clients can automatically register themselves with the identity provider and obtain credentials without any manual configuration.+`RemoteAuthProvider` enables authentication with identity providers that **support Dynamic Client Registration (DCR)**, such as Descope and WorkOS AuthKit. With DCR, MCP clients can automatically register themselves with the identity provider and obtain credentials without any manual configuration.This class combines token validation with OAuth discovery metadata. It extends `TokenVerifier` functionality by adding OAuth 2.0 protected resource endpoints that advertise your authentication requirements. MCP clients examine these endpoints to understand which identity providers you trust and how to obtain valid tokens.@@ -258,7 +258,7 @@ The authentication approach you choose depends on your existing infrastructure,**For OAuth providers without DCR support (GitHub, Google, Azure, most enterprise systems), use OAuth Proxy.** These providers require manual app registration through their developer consoles. OAuth Proxy bridges the gap by presenting a DCR-compliant interface to MCP clients while using your fixed credentials with the provider. The proxy's callback forwarding pattern enables dynamic client ports to work with providers that require fixed redirect URIs.-**For identity providers with DCR support (WorkOS AuthKit, modern auth platforms), use RemoteAuthProvider.** These providers allow clients to dynamically register and obtain credentials without manual configuration. This enables the fully automated authentication flow that MCP is designed for, providing the best user experience and simplest implementation.+**For identity providers with DCR support (Descope, WorkOS AuthKit, modern auth platforms), use RemoteAuthProvider.** These providers allow clients to dynamically register and obtain credentials without manual configuration. This enables the fully automated authentication flow that MCP is designed for, providing the best user experience and simplest implementation.**Token validation works well when you already have authentication infrastructure that issues structured tokens.** If your organization already uses JWT-based systems, API gateways, or enterprise SSO that can generate tokens, this approach integrates seamlessly while keeping your MCP server focused on its core functionality. The simplicity comes from leveraging existing investment in authentication infrastructure.diff --git a/docs/servers/auth/oauth-proxy.mdx b/docs/servers/auth/oauth-proxy.mdxindex 1e31a33e7..32b894a58 100644--- a/docs/servers/auth/oauth-proxy.mdx+++ b/docs/servers/auth/oauth-proxy.mdx@@ -10,7 +10,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx";<VersionBadge version="2.12.0" />-OAuth Proxy enables FastMCP servers to authenticate with OAuth providers that **don't support Dynamic Client Registration (DCR)**. This includes virtually all traditional OAuth providers: GitHub, Google, Azure, Discord, Facebook, and most enterprise identity systems. For providers that do support DCR (like WorkOS AuthKit), use [`RemoteAuthProvider`](/servers/auth/remote-oauth) instead.+OAuth Proxy enables FastMCP servers to authenticate with OAuth providers that **don't support Dynamic Client Registration (DCR)**. This includes virtually all traditional OAuth providers: GitHub, Google, Azure, Discord, Facebook, and most enterprise identity systems. For providers that do support DCR (like Descope and WorkOS AuthKit), use [`RemoteAuthProvider`](/servers/auth/remote-oauth) instead.MCP clients expect to register automatically and obtain credentials on the fly, but traditional providers require manual app registration through their developer consoles. OAuth Proxy bridges this gap by presenting a DCR-compliant interface to MCP clients while using your pre-registered credentials with the upstream provider. When a client attempts to register, the proxy returns your fixed credentials. When a client initiates authorization, the proxy handles the complexity of callback forwarding—storing the client's dynamic callback URL, using its own fixed callback with the provider, then forwarding back to the client after token exchange.diff --git a/docs/servers/auth/remote-oauth.mdx b/docs/servers/auth/remote-oauth.mdxindex 99d5b3121..299a15950 100644--- a/docs/servers/auth/remote-oauth.mdx+++ b/docs/servers/auth/remote-oauth.mdx@@ -1,7 +1,7 @@---title: Remote OAuthsidebarTitle: Remote OAuth-description: Integrate your FastMCP server with external identity providers like WorkOS, Auth0, and corporate SSO systems.+description: Integrate your FastMCP server with external identity providers like Descope, WorkOS, Auth0, and corporate SSO systems.icon: camera-cctvtag: NEW---@@ -14,7 +14,7 @@ Remote OAuth integration allows your FastMCP server to leverage external identit<Tip>**When to use RemoteAuthProvider vs OAuth Proxy:**-- **RemoteAuthProvider**: For providers WITH Dynamic Client Registration (WorkOS AuthKit, modern OIDC providers)+- **RemoteAuthProvider**: For providers WITH Dynamic Client Registration (Descope, WorkOS AuthKit, modern OIDC providers)- **OAuth Proxy**: For providers WITHOUT Dynamic Client Registration (GitHub, Google, Azure, Discord, etc.)RemoteAuthProvider requires DCR support for fully automated client registration and authentication.@@ -29,7 +29,7 @@ RemoteAuthProvider works with identity providers that support **Dynamic Client R| **Client Registration** | Automatic via API | Manual in provider console || **Credentials** | Dynamic per client | Fixed app credentials || **Configuration** | Zero client config | Pre-shared credentials |-| **Examples** | WorkOS AuthKit, modern OIDC | GitHub, Google, Azure |+| **Examples** | Descope, WorkOS AuthKit, modern OIDC | GitHub, Google, Azure || **FastMCP Class** | `RemoteAuthProvider` | [`OAuthProxy`](/servers/auth/oauth-proxy) |If your provider doesn't support DCR (most traditional OAuth providers), you'll need to use [`OAuth Proxy`](/servers/auth/oauth-proxy) instead, which bridges the gap between MCP's DCR expectations and fixed OAuth credentials.diff --git a/src/fastmcp/server/auth/providers/descope.py b/src/fastmcp/server/auth/providers/descope.pynew file mode 100644index 000000000..1195cdfb9--- /dev/null+++ b/src/fastmcp/server/auth/providers/descope.py@@ -0,0 +1,172 @@+"""Descope authentication provider for FastMCP.++This module provides DescopeProvider - a complete authentication solution that integrates+with Descope's OAuth 2.1 and OpenID Connect services, supporting Dynamic Client Registration (DCR)+for seamless MCP client authentication.+"""++from __future__ import annotations++from typing import Any++import httpx+from pydantic import AnyHttpUrl+from pydantic_settings import BaseSettings, SettingsConfigDict+from starlette.responses import JSONResponse+from starlette.routing import Route++from fastmcp.server.auth import RemoteAuthProvider, TokenVerifier+from fastmcp.server.auth.providers.jwt import JWTVerifier+from fastmcp.utilities.logging import get_logger+from fastmcp.utilities.types import NotSet, NotSetT++logger = get_logger(__name__)+++class DescopeProviderSettings(BaseSettings):+ model_config = SettingsConfigDict(+ env_prefix="FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_",+ env_file=".env",+ extra="ignore",+ )++ project_id: str+ base_url: AnyHttpUrl+ descope_base_url: AnyHttpUrl = AnyHttpUrl("https://api.descope.com")+++class DescopeProvider(RemoteAuthProvider):+ """Descope metadata provider for DCR (Dynamic Client Registration).++ This provider implements Descope integration using metadata forwarding.+ This is the recommended approach for Descope DCR+ as it allows Descope to handle the OAuth flow directly while FastMCP acts+ as a resource server.++ IMPORTANT SETUP REQUIREMENTS:++ 1. Enable Dynamic Client Registration in Descope Console:+ - Go to the [Inbound Apps page](https://app.descope.com/apps/inbound) of the Descope Console+ - Click **DCR Settings**+ - Enable **Dynamic Client Registration (DCR)**+ - Define allowed scopes++ 2. Note your Project ID:+ - Save your Project ID from [Project Settings](https://app.descope.com/settings/project)+ - Example: P2abc...123++ For detailed setup instructions, see:+ https://docs.descope.com/identity-federation/inbound-apps/creating-inbound-apps#method-2-dynamic-client-registration-dcr++ Example:+ ```python+ from fastmcp.server.auth.providers.descope import DescopeProvider++ # Create Descope metadata provider (JWT verifier created automatically)+ descope_auth = DescopeProvider(+ project_id="P2abc...123",+ base_url="https://your-fastmcp-server.com",+ descope_base_url="https://api.descope.com",+ )++ # Use with FastMCP+ mcp = FastMCP("My App", auth=descope_auth)+ ```+ """++ def __init__(+ self,+ *,+ project_id: str | NotSetT = NotSet,+ base_url: AnyHttpUrl | str | NotSetT = NotSet,+ descope_base_url: AnyHttpUrl | str | NotSetT = NotSet,+ token_verifier: TokenVerifier | None = None,+ ):+ """Initialize Descope metadata provider.++ Args:+ project_id: Your Descope Project ID (e.g., "P2abc...123")+ base_url: Public URL of this FastMCP server+ descope_base_url: Descope API base URL (defaults to https://api.descope.com)+ token_verifier: Optional token verifier. If None, creates JWT verifier for Descope+ """+ settings = DescopeProviderSettings.model_validate(+ {+ k: v+ for k, v in {+ "project_id": project_id,+ "base_url": base_url,+ "descope_base_url": descope_base_url,+ }.items()+ if v is not NotSet+ }+ )++ self.project_id = settings.project_id+ self.base_url = str(settings.base_url).rstrip("/")+ self.descope_base_url = str(settings.descope_base_url).rstrip("/")++ # Create default JWT verifier if none provided+ if token_verifier is None:+ token_verifier = JWTVerifier(+ jwks_uri=f"{self.descope_base_url}/{self.project_id}/.well-known/jwks.json",+ issuer=f"{self.descope_base_url}/v1/apps/{self.project_id}",+ algorithm="RS256",+ audience=self.project_id,+ )++ # Initialize RemoteAuthProvider with Descope as the authorization server+ super().__init__(+ token_verifier=token_verifier,+ authorization_servers=[+ AnyHttpUrl(f"{self.descope_base_url}/v1/apps/{self.project_id}")+ ],+ base_url=self.base_url,+ )++ def get_routes(+ self,+ mcp_path: str | None = None,+ mcp_endpoint: Any | None = None,+ ) -> list[Route]:+ """Get OAuth routes including Descope authorization server metadata forwarding.++ This returns the standard protected resource routes plus an authorization server+ metadata endpoint that forwards Descope's OAuth metadata to clients.++ Args:+ mcp_path: The path where the MCP endpoint is mounted (e.g., "/mcp")+ mcp_endpoint: The MCP endpoint handler to protect with auth+ """+ # Get the standard protected resource routes from RemoteAuthProvider+ routes = super().get_routes(mcp_path, mcp_endpoint)++ async def oauth_authorization_server_metadata(request):+ """Forward Descope OAuth authorization server metadata with FastMCP customizations."""+ try:+ async with httpx.AsyncClient() as client:+ response = await client.get(+ f"{self.descope_base_url}/v1/apps/{self.project_id}/.well-known/oauth-authorization-server"+ )+ response.raise_for_status()+ metadata = response.json()+ return JSONResponse(metadata)+ except Exception as e:+ return JSONResponse(+ {+ "error": "server_error",+ "error_description": f"Failed to fetch Descope metadata: {e}",+ },+ status_code=500,+ )++ # Add Descope authorization server metadata forwarding+ routes.append(+ Route(+ "/.well-known/oauth-authorization-server",+ endpoint=oauth_authorization_server_metadata,+ methods=["GET"],+ )+ )++ return routesdiff --git a/tests/server/auth/providers/test_descope.py b/tests/server/auth/providers/test_descope.pynew file mode 100644index 000000000..e59ec9567--- /dev/null+++ b/tests/server/auth/providers/test_descope.py@@ -0,0 +1,170 @@+"""Tests for Descope OAuth provider."""++import os+from collections.abc import Generator+from unittest.mock import patch++import httpx+import pytest++from fastmcp import Client, FastMCP+from fastmcp.client.transports import StreamableHttpTransport+from fastmcp.server.auth.providers.descope import DescopeProvider+from fastmcp.utilities.tests import HeadlessOAuth, run_server_in_process+++class TestDescopeProvider:+ """Test Descope OAuth provider functionality."""++ def test_init_with_explicit_params(self):+ """Test DescopeProvider initialization with explicit parameters."""+ provider = DescopeProvider(+ project_id="P2abc123",+ base_url="https://myserver.com",+ descope_base_url="https://api.descope.com",+ )++ assert provider.project_id == "P2abc123"+ assert str(provider.base_url) == "https://myserver.com/"+ assert str(provider.descope_base_url) == "https://api.descope.com"++ @pytest.mark.parametrize(+ "scopes_env",+ [+ "openid,email",+ '["openid", "email"]',+ ],+ )+ def test_init_with_env_vars(self, scopes_env):+ """Test DescopeProvider initialization from environment variables."""+ with patch.dict(+ os.environ,+ {+ "FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_PROJECT_ID": "P2env123",+ "FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_BASE_URL": "https://envserver.com",+ "FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_DESCOPE_BASE_URL": "https://api.descope.com",+ },+ ):+ provider = DescopeProvider()++ assert provider.project_id == "P2env123"+ assert str(provider.base_url) == "https://envserver.com/"+ assert str(provider.descope_base_url) == "https://api.descope.com"++ def test_environment_variable_loading(self):+ """Test that environment variables are loaded correctly."""+ # This test verifies that the provider can be created with environment variables+ provider = DescopeProvider(+ project_id="P2env123", base_url="http://env-server.com"+ )++ # Should have loaded from environment+ assert provider.project_id == "P2env123"+ assert str(provider.base_url) == "http://env-server.com/"+ assert str(provider.descope_base_url) == "https://api.descope.com"++ def test_descope_base_url_https_prefix_handling(self):+ """Test that descope_base_url handles missing https:// prefix."""+ # Without https:// - should add it+ provider1 = DescopeProvider(+ project_id="P2abc123",+ base_url="https://myserver.com",+ descope_base_url="https://api.descope.com",+ )+ assert str(provider1.descope_base_url) == "https://api.descope.com"++ # With https:// - should keep it+ provider2 = DescopeProvider(+ project_id="P2abc123",+ base_url="https://myserver.com",+ descope_base_url="https://api.descope.com",+ )+ assert str(provider2.descope_base_url) == "https://api.descope.com"++ # With http:// - should be preserved+ provider3 = DescopeProvider(+ project_id="P2abc123",+ base_url="https://myserver.com",+ descope_base_url="http://localhost:8080",+ )+ assert str(provider3.descope_base_url) == "http://localhost:8080"++ def test_init_defaults(self):+ """Test that default values are applied correctly."""+ provider = DescopeProvider(+ project_id="P2abc123",+ base_url="https://myserver.com",+ )++ # Check defaults+ assert str(provider.descope_base_url) == "https://api.descope.com"++ def test_jwt_verifier_configured_correctly(self):+ """Test that JWT verifier is configured correctly."""+ provider = DescopeProvider(+ project_id="P2abc123",+ base_url="https://myserver.com",+ descope_base_url="https://api.descope.com",+ )++ # Check that JWT verifier uses the correct endpoints+ assert (+ provider.token_verifier.jwks_uri # type: ignore[attr-defined]+ == "https://api.descope.com/P2abc123/.well-known/jwks.json"+ )+ assert (+ provider.token_verifier.issuer == "https://api.descope.com/v1/apps/P2abc123" # type: ignore[attr-defined]+ )+ assert provider.token_verifier.audience == "P2abc123" # type: ignore[attr-defined]+++def run_mcp_server(host: str, port: int) -> None:+ mcp = FastMCP(+ auth=DescopeProvider(+ project_id="P2test123",+ base_url="http://localhost:4321",+ descope_base_url="https://api.descope.com",+ )+ )++ @mcp.tool+ def add(a: int, b: int) -> int:+ return a + b++ mcp.run(host=host, port=port, transport="http")++[email protected](scope="module")+def mcp_server_url() -> Generator[str]:+ with run_server_in_process(run_mcp_server) as url:+ yield f"{url}/mcp"+++def client_with_headless_oauth(+ mcp_server_url: str,+) -> Generator[Client, None, None]:+ """Client with headless OAuth that bypasses browser interaction."""+ client = Client(+ transport=StreamableHttpTransport(mcp_server_url),+ auth=HeadlessOAuth(mcp_url=mcp_server_url),+ )+ yield client+++class TestDescopeProviderIntegration:+ async def test_unauthorized_access(self, mcp_server_url: str):+ with pytest.raises(httpx.HTTPStatusError) as exc_info:+ async with Client(mcp_server_url) as client:+ tools = await client.list_tools() # noqa: F841++ assert isinstance(exc_info.value, httpx.HTTPStatusError)+ assert exc_info.value.response.status_code == 401+ assert "tools" not in locals()++ # async def test_authorized_access(self, client_with_headless_oauth: Client):+ # async with client_with_headless_oauth:+ # tools = await client_with_headless_oauth.list_tools()+ # assert tools is not None+ # assert len(tools) > 0+ # assert "add" in tools