π The fast, Pythonic way to build MCP servers and clients.
feat: Add support for OIDC configuration (#1817)
Ruhul Alam972521146f67
diff --git a/docs/docs.json b/docs/docs.jsonindex 02cbd9d27..87fac42a3 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -97,6 +97,7 @@"servers/auth/token-verification","servers/auth/remote-oauth","servers/auth/oauth-proxy",+ "servers/auth/oidc-proxy","servers/auth/full-oauth-server"]},@@ -161,6 +162,7 @@"group": "Authentication","icon": "key","pages": [+ "integrations/auth0","integrations/authkit","integrations/azure","integrations/github",diff --git a/docs/integrations/auth0.mdx b/docs/integrations/auth0.mdxnew file mode 100644index 000000000..0c8b9ff48--- /dev/null+++ b/docs/integrations/auth0.mdx@@ -0,0 +1,231 @@+---+title: Auth0 OAuth π€ FastMCP+sidebarTitle: Auth0+description: Secure your FastMCP server with Auth0 OAuth+icon: shield-check+tag: NEW+---++import { VersionBadge } from "/snippets/version-badge.mdx"++<VersionBadge version="2.12.4" />++This guide shows you how to secure your FastMCP server using **Auth0 OAuth**. While Auth0 does have support for Dynamic Client Registration, it is not enabled by default so this integration uses the [**OIDC Proxy**](/servers/auth/oidc-proxy) pattern to bridge Auth0's dynamic OIDC configuration with MCP's authentication requirements.++## Configuration++### Prerequisites++Before you begin, you will need:+1. An **[Auth0 Account](https://auth0.com/)** with access to create Applications+2. Your FastMCP server's URL (can be localhost for development, e.g., `http://localhost:8000`)++### Step 1: Create an Auth0 Application++Create an Application in your Auth0 settings to get the credentials needed for authentication:++<Steps>+<Step title="Navigate to Applications">+ Go to **Applications β Applications** in your Auth0 account.++ Click **"+ Create Application"** to create a new application.+</Step>++<Step title="Create Your Application">+ - **Name**: Choose a name users will recognize (e.g., "My FastMCP Server")+ - **Choose an application type**: Choose "Single Page Web Applications"+ - Click **Create** to create the application+</Step>++<Step title="Configure Your Application">+ Select the "Settings" tab for your application, then find the "Application URIs" section.++ - **Allowed Callback URLs**: Your server URL + `/auth/callback` (e.g., `http://localhost:8000/auth/callback`)+ - Click **Save** to save your changes++ <Warning>+ The callback URL must match exactly. The default path is `/auth/callback`, but you can customize it using the `redirect_path` parameter.+ </Warning>++ <Tip>+ If you want to use a custom callback path (e.g., `/auth/auth0/callback`), make sure to set the same path in both your Auth0 Application settings and the `redirect_path` parameter when configuring the Auth0Provider.+ </Tip>+</Step>++<Step title="Save Your Credentials">+ After creating the app, in the "Basic Information" section you'll see:++ - **Client ID**: A public identifier like `tv2ObNgaZAWWhhycr7Bz1LU2mxlnsmsB`+ - **Client Secret**: A private hidden value that should always be stored securely++ <Tip>+ Store these credentials securely. Never commit them to version control. Use environment variables or a secrets manager in production.+ </Tip>+</Step>++<Step title="Select Your Audience">+ Go to **Applications β APIs** in your Auth0 account.++ - Find the API that you want to use for your application+ - **API Audience**: A URL that uniquely identifies the API++ <Tip>+ Store this along with of the credentials above. Never commit this to version control. Use environment variables or a secrets manager in production.+ </Tip>+</Step>+</Steps>++### Step 2: FastMCP Configuration++Create your FastMCP server using the `Auth0Provider`.++```python server.py+from fastmcp import FastMCP+from fastmcp.server.auth.providers.auth0 import Auth0Provider++# The Auth0Provider utilizes Auth0 OIDC configuration+auth_provider = Auth0Provider(+ config_url="https://.../.well-known/openid-configuration", # Your Auth0 configuration URL+ client_id="tv2ObNgaZAWWhhycr7Bz1LU2mxlnsmsB", # Your Auth0 application Client ID+ client_secret="vPYqbjemq...", # Your Auth0 application Client Secret+ audience="https://...", # Your Auth0 API audience+ base_url="http://localhost:8000", # Must match your application configuration+ # redirect_path="/auth/callback" # Default value, customize if needed+)++mcp = FastMCP(name="Auth0 Secured App", auth=auth_provider)++# Add a protected tool to test authentication+async def get_token_info() -> dict:+ """Returns information about the Auth0 token."""+ from fastmcp.server.dependencies import get_access_token++ token = get_access_token()++ return {+ "issuer": token.claims.get("iss"),+ "audience": token.claims.get("aud"),+ "scope": token.claims.get("scope")+ }+```++## Testing++### Running the Server++Start your FastMCP server with HTTP transport to enable OAuth flows:++```bash+fastmcp run server.py --transport http --port 8000+```++Your server is now running and protected by Auth0 authentication.++### Testing with a Client++Create a test client that authenticates with your Auth0-protected server:++```python test_client.py+from fastmcp import Client+import asyncio++async def main():+ # The client will automatically handle Auth0 OAuth flows+ async with Client("http://localhost:8000/mcp/", auth="oauth") as client:+ # First-time connection will open Auth0 login in your browser+ print("β Authenticated with Auth0!")++ # Test the protected tool+ result = await client.call_tool("get_token_info")+ print(f"Auth0 audience: {result['audience']}")++if __name__ == "__main__":+ asyncio.run(main())+```++When you run the client for the first time:+1. Your browser will open to Auth0's authorization page+2. After you authorize the app, you'll be redirected back+3. The client receives the token and can make authenticated requests++<Info>+The client caches tokens locally, so you won't need to re-authenticate for subsequent runs unless the token expires or you explicitly clear the cache.+</Info>++## Environment Variables++For production deployments, use environment variables instead of hardcoding credentials.++### Provider Selection++Setting this environment variable allows the Auth0 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.auth0.Auth0Provider` to use Auth0 authentication.+</ParamField>+</Card>++### Auth0-Specific Configuration++These environment variables provide default values for the Auth0 provider, whether it's instantiated manually or configured via `FASTMCP_SERVER_AUTH`.++<Card>+<ParamField path="FASTMCP_SERVER_AUTH_AUTH0_CONFIG_URL" required>+Your Auth0 Application Configuration URL (e.g., `https://.../.well-known/openid-configuration`)+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID" required>+Your Auth0 Application Client ID (e.g., `tv2ObNgaZAWWhhycr7Bz1LU2mxlnsmsB`)+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET" required>+Your Auth0 Application Client Secret (e.g., `vPYqbjemq...`)+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE" required>+Your Auth0 API Audience+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_AUTH0_BASE_URL" required>+Public URL of your FastMCP server for OAuth callbacks+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_AUTH0_REDIRECT_PATH" default="/auth/callback">+Redirect path configured in your Auth0 Application+</ParamField>++<ParamField path="FASTMCP_SERVER_AUTH_AUTH0_REQUIRED_SCOPES" default='["openid"]'>+Comma-, space-, or JSON-separated list of required AUth0 scopes (e.g., `openid email` or `["openid","email"]`)+</ParamField>+</Card>++Example `.env` file:+```bash+# Use the Auth0 provider+FASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.auth0.Auth0Provider++# Auth0 configuration and credentials+FASTMCP_SERVER_AUTH_AUTH0_CONFIG_URL=https://.../.well-known/openid-configuration+FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID=tv2ObNgaZAWWhhycr7Bz1LU2mxlnsmsB+FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET=vPYqbjemq...+FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE=https://...+FASTMCP_SERVER_AUTH_AUTH0_BASE_URL=https://your-server.com+FASTMCP_SERVER_AUTH_AUTH0_REQUIRED_SCOPES=openid,email+```++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="Auth0 Secured App")++async def search_logs() -> list[str]:+ """Search the service logs."""+ # Your tool implementation here+ pass+```diff --git a/docs/servers/auth/oidc-proxy.mdx b/docs/servers/auth/oidc-proxy.mdxnew file mode 100644index 000000000..9b7b29ad7--- /dev/null+++ b/docs/servers/auth/oidc-proxy.mdx@@ -0,0 +1,185 @@+---+title: OIDC Proxy+sidebarTitle: OIDC Proxy+description: Bridge OIDC providers to work seamlessly with MCP's authentication flow.+icon: share+tag: NEW+---++import { VersionBadge } from "/snippets/version-badge.mdx";++<VersionBadge version="2.12.4" />++OIDC Proxy enables FastMCP servers to authenticate with OIDC providers that **don't support Dynamic Client Registration (DCR)** out of the box. This includes OAuth providers like: Auth0, Google, Azure, etc. For providers that do support DCR (like WorkOS AuthKit), use [`RemoteAuthProvider`](/servers/auth/remote-oauth) instead.++The OIDC Proxy is built upon [`OAuthProxy`](/servers/auth/oauth-proxy) so it has all the same functionality under the covers.++## Implementation++### Provider Setup Requirements++Before using OIDC Proxy, you need to register your application with your OAuth provider:++1. **Register your application** in the provider's developer console (Auth0 Applications, Google Cloud Console, Azure Portal, etc.)+2. **Configure the redirect URI** as your FastMCP server URL plus your chosen callback path:+ - Default: `https://your-server.com/auth/callback`+ - Custom: `https://your-server.com/your/custom/path` (if you set `redirect_path`)+ - Development: `http://localhost:8000/auth/callback`+3. **Obtain your credentials**: Client ID and Client Secret++<Warning>+ The redirect URI you configure with your provider must exactly match your+ FastMCP server's URL plus the callback path. If you customize `redirect_path`+ in OAuth Proxy, update your provider's redirect URI accordingly.+</Warning>++### Basic Setup++Here's how to implement OIDC Proxy with any provider:++```python+from fastmcp import FastMCP+from fastmcp.server.auth.oidc_proxy import OIDCProxy++# Create the OIDC proxy+auth = OIDCProxy(+ # Provider's configuration URL+ config_url="https://provider.com/.well-known/openid-configuration",++ # Your registered app credentials+ client_id="your-client-id",+ client_secret="your-client-secret",++ # Your FastMCP server's public URL+ base_url="https://your-server.com",++ # Optional: customize the callback path (default is "/auth/callback")+ # redirect_path="/custom/callback",+)++mcp = FastMCP(name="My Server", auth=auth)+```++### Configuration Parameters++<Card icon="code" title="OIDCProxy Parameters">+<ParamField body="config_url" type="str" required>+ URL of your OAuth provider's OIDC configuration+</ParamField>++<ParamField body="client_id" type="str" required>+ Client ID from your registered OAuth application+</ParamField>++<ParamField body="client_secret" type="str" required>+ Client secret from your registered OAuth application+</ParamField>++<ParamField body="base_url" type="AnyHttpUrl | str" required>+ Public URL of your FastMCP server (e.g., `https://your-server.com`)+</ParamField>++<ParamField body="strict" type="str">+ Strict flag for configuration validation+</ParamField>++<ParamField body="audience" type="str">+ Audience from your registered OAuth application+</ParamField>++<ParamField body="timeout_seconds" type="str">+ HTTP request timeout in seconds+</ParamField>++<ParamField body="algorithm" type="str">+ The algorithm for the token verifier+</ParamField>++<ParamField body="required_scopes" type="str">+ The required scopes for the token verifier+</ParamField>++<ParamField body="redirect_path" type="str" default="/auth/callback">+ Path for OAuth callbacks. Must match the redirect URI configured in your OAuth application+</ParamField>++<ParamField body="allowed_client_redirect_uris" type="list[str] | None">+ List of allowed redirect URI patterns for MCP clients. Patterns support wildcards (e.g., `"http://localhost:*"`, `"https://*.example.com/*"`).+ - `None` (default): All redirect URIs allowed (for MCP/DCR compatibility)+ - Empty list `[]`: No redirect URIs allowed+ - Custom list: Only matching patterns allowed++ These patterns apply to MCP client loopback redirects, NOT the upstream OAuth app redirect URI.+</ParamField>++<ParamField body="token_endpoint_auth_method" type="str | None">+ Token endpoint authentication method for the upstream OAuth server. Controls how the proxy authenticates when exchanging authorization codes and refresh tokens with the upstream provider.+ - `"client_secret_basic"`: Send credentials in Authorization header (most common)+ - `"client_secret_post"`: Send credentials in request body (required by some providers)+ - `"none"`: No authentication (for public clients)+ - `None` (default): Uses authlib's default (typically `"client_secret_basic"`)++ Set this if your provider requires a specific authentication method and the default doesn't work.+</ParamField>+</Card>++### Using Built-in Providers++FastMCP includes pre-configured OIDC providers for common services:++```python+from fastmcp.server.auth.providers.auth0 import Auth0Provider++auth = Auth0Provider(+ config_url="https://.../.well-known/openid-configuration",+ client_id="your-auth0-client-id",+ client_secret="your-auth0-client-secret",+ audience="https://...",+ base_url="https://localhost:8000"+)++mcp = FastMCP(name="My Server", auth=auth)+```++Available providers include `Auth0Provider` at present.++### Scope Configuration++OAuth scopes are configured with `required_scopes` to automatically request the permissions your application needs.++Dynamic clients created by the proxy will automatically include these scopes in their authorization requests.++## Environment Configuration++<VersionBadge version="2.13.0" />++For production deployments, configure OIDC Proxy through environment variables instead of hardcoding credentials:++```bash+# Specify the provider implementation+export FASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.auth0.Auth0Provider++# Provider-specific credentials+export FASTMCP_SERVER_AUTH_AUTH0_CONFIG_URL=https://.../.well-known/openid-configuration+export FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID=tv2ObNgaZAWWhhycr7Bz1LU2mxlnsmsB+export FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET=vPYqbjemq...+export FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE=https://...+export FASTMCP_SERVER_AUTH_AUTH0_BASE_URL=https://localhost:8000+```++With environment configuration, your server code simplifies to:++```python+from fastmcp import FastMCP++# Authentication automatically configured from environment+mcp = FastMCP(name="My Server")++def protected_tool(data: str) -> str:+ """This tool is now protected by OAuth."""+ return f"Processed: {data}"++if __name__ == "__main__":+ mcp.run(transport="http", port=8000)+```diff --git a/src/fastmcp/server/auth/oidc_proxy.py b/src/fastmcp/server/auth/oidc_proxy.pynew file mode 100644index 000000000..268b849b2--- /dev/null+++ b/src/fastmcp/server/auth/oidc_proxy.py@@ -0,0 +1,332 @@+"""OIDC Proxy Provider for FastMCP.++This provider acts as a transparent proxy to an upstream OIDC compliant Authorization+Server. It leverages the OAuthProxy class to handle Dynamic Client Registration and+forwarding of all OAuth flows.++This implementation is based on:+ OpenID Connect Discovery 1.0 - https://openid.net/specs/openid-connect-discovery-1_0.html+ OAuth 2.0 Authorization Server Metadata - https://datatracker.ietf.org/doc/html/rfc8414+"""++from collections.abc import Sequence++import httpx+from pydantic import AnyHttpUrl, BaseModel, model_validator+from typing_extensions import Self++from fastmcp.server.auth import TokenVerifier+from fastmcp.server.auth.oauth_proxy import OAuthProxy+from fastmcp.server.auth.providers.jwt import JWTVerifier+from fastmcp.utilities.logging import get_logger++logger = get_logger(__name__)+++class OIDCConfiguration(BaseModel):+ """OIDC Configuration.++ See:+ https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata+ https://datatracker.ietf.org/doc/html/rfc8414#section-2+ """++ strict: bool = True++ # OpenID Connect Discovery 1.0+ issuer: AnyHttpUrl | None = None # Strict++ authorization_endpoint: AnyHttpUrl | None = None # Strict+ token_endpoint: AnyHttpUrl | None = None # Strict+ userinfo_endpoint: AnyHttpUrl | None = None++ jwks_uri: AnyHttpUrl | None = None # Strict++ registration_endpoint: AnyHttpUrl | None = None++ scopes_supported: Sequence[str] | None = None++ response_types_supported: Sequence[str] | None = None # Strict+ response_modes_supported: Sequence[str] | None = None++ grant_types_supported: Sequence[str] | None = None++ acr_values_supported: Sequence[str] | None = None++ subject_types_supported: Sequence[str] | None = None # Strict++ id_token_signing_alg_values_supported: Sequence[str] | None = None # Strict+ id_token_encryption_alg_values_supported: Sequence[str] | None = None+ id_token_encryption_enc_values_supported: Sequence[str] | None = None++ userinfo_signing_alg_values_supported: Sequence[str] | None = None+ userinfo_encryption_alg_values_supported: Sequence[str] | None = None+ userinfo_encryption_enc_values_supported: Sequence[str] | None = None++ request_object_signing_alg_values_supported: Sequence[str] | None = None+ request_object_encryption_alg_values_supported: Sequence[str] | None = None+ request_object_encryption_enc_values_supported: Sequence[str] | None = None++ token_endpoint_auth_methods_supported: Sequence[str] | None = None+ token_endpoint_auth_signing_alg_values_supported: Sequence[str] | None = None++ display_values_supported: Sequence[str] | None = None++ claim_types_supported: Sequence[str] | None = None+ claims_supported: Sequence[str] | None = None++ service_documentation: AnyHttpUrl | None = None++ claims_locales_supported: Sequence[str] | None = None+ ui_locales_supported: Sequence[str] | None = None++ claims_parameter_supported: bool | None = None+ request_parameter_supported: bool | None = None+ request_uri_parameter_supported: bool | None = None++ require_request_uri_registration: bool | None = None++ op_policy_uri: AnyHttpUrl | None = None+ op_tos_uri: AnyHttpUrl | None = None++ # OAuth 2.0 Authorization Server Metadata+ revocation_endpoint: AnyHttpUrl | None = None+ revocation_endpoint_auth_methods_supported: Sequence[str] | None = None+ revocation_endpoint_auth_signing_alg_values_supported: Sequence[str] | None = None++ introspection_endpoint: AnyHttpUrl | None = None+ introspection_endpoint_auth_methods_supported: Sequence[str] | None = None+ introspection_endpoint_auth_signing_alg_values_supported: Sequence[str] | None = (+ None+ )++ code_challenge_methods_supported: Sequence[str] | None = None++ signed_metadata: str | None = None++ @model_validator(mode="after")+ def _enforce_strict(self) -> Self:+ """Enforce strict rules."""+ if not self.strict:+ return self++ def enforce(attr: str) -> None:+ if not getattr(self, attr, None):+ message = f"Missing required configuration metadata: {attr}"+ logger.error(message)+ raise ValueError(message)++ enforce("issuer")+ enforce("authorization_endpoint")+ enforce("token_endpoint")+ enforce("jwks_uri")+ enforce("response_types_supported")+ enforce("subject_types_supported")+ enforce("id_token_signing_alg_values_supported")++ return self++ @classmethod+ def get_oidc_configuration(+ cls, config_url: AnyHttpUrl, *, strict: bool | None, timeout_seconds: int | None+ ) -> Self:+ """Get the OIDC configuration for the specified config URL.++ Args:+ config_url: The OIDC config URL+ strict: The strict flag for the configuration+ timeout_seconds: HTTP request timeout in seconds+ """+ get_kwargs = {}+ if timeout_seconds is not None:+ get_kwargs["timeout"] = timeout_seconds++ try:+ response = httpx.get(str(config_url), **get_kwargs)+ response.raise_for_status()++ config_data = response.json()+ if strict is not None:+ config_data["strict"] = strict++ return cls.model_validate(config_data)+ except Exception:+ logger.exception(+ f"Unable to get OIDC configuration for config url: {config_url}"+ )+ raise+++class OIDCProxy(OAuthProxy):+ """OAuth provider that wraps OAuthProxy to provide configuration via an OIDC configuration URL.++ This provider makes it easier to add OAuth protection for any upstream provider+ that is OIDC compliant.++ Example:+ ```python+ from fastmcp import FastMCP+ from fastmcp.server.auth.oidc_proxy import OIDCProxy++ # Simple OIDC based protection+ auth = OIDCProxy(+ config_url="https://oidc.config.url",+ client_id="your-oidc-client-id",+ client_secret="your-oidc-client-secret",+ base_url="https://your.server.url",+ )++ mcp = FastMCP("My Protected Server", auth=auth)+ ```+ """++ oidc_config: OIDCConfiguration++ def __init__(+ self,+ *,+ # OIDC configuration+ config_url: AnyHttpUrl | str,+ strict: bool | None = None,+ # Upstream server configuration+ client_id: str,+ client_secret: str,+ audience: str | None = None,+ timeout_seconds: int | None = None,+ # Token verifier+ algorithm: str | None = None,+ required_scopes: list[str] | None = None,+ # FastMCP server configuration+ base_url: AnyHttpUrl | str,+ redirect_path: str | None = None,+ # Client configuration+ allowed_client_redirect_uris: list[str] | None = None,+ # Token validation configuration+ token_endpoint_auth_method: str | None = None,+ ) -> None:+ """Initialize the OIDC proxy provider.++ Args:+ config_url: URL of upstream configuration+ strict: Optional strict flag for the configuration+ client_id: Client ID registered with upstream server+ client_secret: Client secret for upstream server+ audience: Audience for upstream server+ timeout_seconds: HTTP request timeout in seconds+ algorithm: Token verifier algorithm+ required_scopes: Required OAuth scopes+ base_url: Public URL of the server that exposes this FastMCP server; redirect path is+ relative to this URL+ redirect_path: Redirect path configured in upstream OAuth app (defaults to "/auth/callback")+ allowed_client_redirect_uris: List of allowed redirect URI patterns for MCP clients.+ Patterns support wildcards (e.g., "http://localhost:*", "https://*.example.com/*").+ If None (default), only localhost redirect URIs are allowed.+ If empty list, all redirect URIs are allowed (not recommended for production).+ These are for MCP clients performing loopback redirects, NOT for the upstream OAuth app.+ token_endpoint_auth_method: Token endpoint authentication method for upstream server.+ Common values: "client_secret_basic", "client_secret_post", "none".+ If None, authlib will use its default (typically "client_secret_basic").+ """+ if not config_url:+ raise ValueError("Missing required config URL")++ if not client_id:+ raise ValueError("Missing required client id")++ if not client_secret:+ raise ValueError("Missing required client secret")++ if not base_url:+ raise ValueError("Missing required base URL")++ if isinstance(config_url, str):+ config_url = AnyHttpUrl(config_url)++ self.oidc_config = self.get_oidc_configuration(+ config_url, strict, timeout_seconds+ )+ if (+ not self.oidc_config.authorization_endpoint+ or not self.oidc_config.token_endpoint+ ):+ logger.debug(f"Invalid OIDC Configuration: {self.oidc_config}")+ raise ValueError("Missing required OIDC endpoints")++ revocation_endpoint = (+ str(self.oidc_config.revocation_endpoint)+ if self.oidc_config.revocation_endpoint+ else None+ )++ token_verifier = self.get_token_verifier(+ algorithm=algorithm,+ audience=audience,+ required_scopes=required_scopes,+ timeout_seconds=timeout_seconds,+ )++ init_kwargs = {+ "upstream_authorization_endpoint": str(+ self.oidc_config.authorization_endpoint+ ),+ "upstream_token_endpoint": str(self.oidc_config.token_endpoint),+ "upstream_client_id": client_id,+ "upstream_client_secret": client_secret,+ "upstream_revocation_endpoint": revocation_endpoint,+ "token_verifier": token_verifier,+ "base_url": base_url,+ "service_documentation_url": self.oidc_config.service_documentation,+ "allowed_client_redirect_uris": allowed_client_redirect_uris,+ "token_endpoint_auth_method": token_endpoint_auth_method,+ }++ if redirect_path:+ init_kwargs["redirect_path"] = redirect_path++ if audience:+ extra_params = {"audience": audience}+ init_kwargs["extra_authorize_params"] = extra_params+ init_kwargs["extra_token_params"] = extra_params++ super().__init__(**init_kwargs)++ def get_oidc_configuration(+ self,+ config_url: AnyHttpUrl,+ strict: bool | None,+ timeout_seconds: int | None,+ ) -> OIDCConfiguration:+ """Gets the OIDC configuration for the specified configuration URL.++ Args:+ config_url: The OIDC configuration URL+ strict: The strict flag for the configuration+ timeout_seconds: HTTP request timeout in seconds+ """+ return OIDCConfiguration.get_oidc_configuration(+ config_url, strict=strict, timeout_seconds=timeout_seconds+ )++ def get_token_verifier(+ self,+ *,+ algorithm: str | None = None,+ audience: str | None = None,+ required_scopes: list[str] | None = None,+ timeout_seconds: int | None = None,+ ) -> TokenVerifier:+ """Creates the token verifier for the specified OIDC configuration and arguments.++ Args:+ algorithm: Optional token verifier algorithm+ audience: Optional token verifier audience+ required_scopes: Optional token verifier required_scopes+ timeout_seconds: HTTP request timeout in seconds+ """+ return JWTVerifier(+ jwks_uri=str(self.oidc_config.jwks_uri),+ issuer=str(self.oidc_config.issuer),+ algorithm=algorithm,+ audience=audience,+ required_scopes=required_scopes,+ )diff --git a/src/fastmcp/server/auth/providers/auth0.py b/src/fastmcp/server/auth/providers/auth0.pynew file mode 100644index 000000000..8fa6a70af--- /dev/null+++ b/src/fastmcp/server/auth/providers/auth0.py@@ -0,0 +1,171 @@+"""Auth0 OAuth provider for FastMCP.++This module provides a complete Auth0 integration that's ready to use with+just the configuration URL, client ID, client secret, audience, and base URL.++Example:+ ```python+ from fastmcp import FastMCP+ from fastmcp.server.auth.providers.auth0 import Auth0Provider++ # Simple Auth0 OAuth protection+ auth = Auth0Provider(+ config_url="https://auth0.config.url",+ client_id="your-auth0-client-id",+ client_secret="your-auth0-client-secret",+ audience="your-auth0-api-audience",+ base_url="http://localhost:8000",+ )++ mcp = FastMCP("My Protected Server", auth=auth)+ ```+"""++from pydantic import AnyHttpUrl, SecretStr, field_validator+from pydantic_settings import BaseSettings, SettingsConfigDict++from fastmcp.server.auth.oidc_proxy import OIDCProxy+from fastmcp.utilities.auth import parse_scopes+from fastmcp.utilities.logging import get_logger+from fastmcp.utilities.types import NotSet, NotSetT++logger = get_logger(__name__)+++class Auth0ProviderSettings(BaseSettings):+ """Settings for Auth0 OIDC provider."""++ model_config = SettingsConfigDict(+ env_prefix="FASTMCP_SERVER_AUTH_AUTH0_",+ env_file=".env",+ extra="ignore",+ )++ config_url: AnyHttpUrl | None = None+ client_id: str | None = None+ client_secret: SecretStr | None = None+ audience: str | None = None+ base_url: AnyHttpUrl | None = None+ redirect_path: str | None = None+ required_scopes: list[str] | None = None+ allowed_client_redirect_uris: list[str] | None = None++ @field_validator("required_scopes", mode="before")+ @classmethod+ def _parse_scopes(cls, v):+ return parse_scopes(v)+++class Auth0Provider(OIDCProxy):+ """An Auth0 provider implementation for FastMCP.++ This provider is a complete Auth0 integration that's ready to use with+ just the configuration URL, client ID, client secret, audience, and base URL.++ Example:+ ```python+ from fastmcp import FastMCP+ from fastmcp.server.auth.providers.auth0 import Auth0Provider++ # Simple Auth0 OAuth protection+ auth = Auth0Provider(+ config_url="https://auth0.config.url",+ client_id="your-auth0-client-id",+ client_secret="your-auth0-client-secret",+ audience="your-auth0-api-audience",+ base_url="http://localhost:8000",+ )++ mcp = FastMCP("My Protected Server", auth=auth)+ ```+ """++ def __init__(+ self,+ *,+ config_url: AnyHttpUrl | str | NotSetT = NotSet,+ client_id: str | NotSetT = NotSet,+ client_secret: str | NotSetT = NotSet,+ audience: str | NotSetT = NotSet,+ base_url: AnyHttpUrl | str | NotSetT = NotSet,+ required_scopes: list[str] | NotSetT = NotSet,+ redirect_path: str | NotSetT = NotSet,+ allowed_client_redirect_uris: list[str] | NotSetT = NotSet,+ ) -> None:+ """Initialize Auth0 OAuth provider.++ Args:+ config_url: Auth0 config URL+ client_id: Auth0 application client id+ client_secret: Auth0 application client secret+ audience: Auth0 API audience+ base_url: Public URL of your FastMCP server (for OAuth callbacks)+ required_scopes: Required Auth0 scopes (defaults to ["openid"])+ redirect_path: Redirect path configured in Auth0 application+ 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.+ """+ settings = Auth0ProviderSettings.model_validate(+ {+ k: v+ for k, v in {+ "config_url": config_url,+ "client_id": client_id,+ "client_secret": client_secret,+ "audience": audience,+ "base_url": base_url,+ "required_scopes": required_scopes,+ "redirect_path": redirect_path,+ "allowed_client_redirect_uris": allowed_client_redirect_uris,+ }.items()+ if v is not NotSet+ }+ )++ if not settings.config_url:+ raise ValueError(+ "config_url is required - set via parameter or FASTMCP_SERVER_AUTH_AUTH0_CONFIG_URL"+ )++ if not settings.client_id:+ raise ValueError(+ "client_id is required - set via parameter or FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID"+ )++ if not settings.client_secret:+ raise ValueError(+ "client_secret is required - set via parameter or FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET"+ )++ if not settings.audience:+ raise ValueError(+ "audience is required - set via parameter or FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE"+ )++ if not settings.base_url:+ raise ValueError(+ "base_url is required - set via parameter or FASTMCP_SERVER_AUTH_AUTH0_BASE_URL"+ )++ auth0_required_scopes = settings.required_scopes or ["openid"]++ init_kwargs = {+ "config_url": settings.config_url,+ "client_id": settings.client_id,+ "client_secret": settings.client_secret.get_secret_value(),+ "audience": settings.audience,+ "base_url": settings.base_url,+ "required_scopes": auth0_required_scopes,+ "allowed_client_redirect_uris": settings.allowed_client_redirect_uris,+ }++ if settings.redirect_path:+ init_kwargs["redirect_path"] = settings.redirect_path++ super().__init__(**init_kwargs)++ logger.info(+ "Initialized Auth0 OAuth provider for client %s with scopes: %s",+ settings.client_id,+ auth0_required_scopes,+ )diff --git a/tests/server/auth/providers/test_auth0.py b/tests/server/auth/providers/test_auth0.pynew file mode 100644index 000000000..a67643ca0--- /dev/null+++ b/tests/server/auth/providers/test_auth0.py@@ -0,0 +1,275 @@+"""Unit tests for Auth0 OAuth provider."""++import os+from unittest.mock import patch++import pytest++from fastmcp.server.auth.oidc_proxy import OIDCConfiguration+from fastmcp.server.auth.providers.auth0 import Auth0Provider, Auth0ProviderSettings+from fastmcp.server.auth.providers.jwt import JWTVerifier++TEST_CONFIG_URL = "https://example.com/.well-known/openid-configuration"+TEST_CLIENT_ID = "test-client-id"+TEST_CLIENT_SECRET = "test-client-secret"+TEST_AUDIENCE = "test-audience"+TEST_BASE_URL = "https://example.com:8000/"+TEST_REDIRECT_PATH = "/test/callback"+TEST_REQUIRED_SCOPES = ["openid", "email"]+++def valid_oidc_configuration_dict():+ """Create a valid OIDC configuration dict for testing."""+ return {+ "issuer": "https://example.com",+ "authorization_endpoint": "https://example.com/authorize",+ "token_endpoint": "https://example.com/oauth/token",+ "jwks_uri": "https://example.com/.well-known/jwks.json",+ "response_types_supported": ["code"],+ "subject_types_supported": ["public"],+ "id_token_signing_alg_values_supported": ["RS256"],+ }+++class TestAuth0ProviderSettings:+ """Test settings for Auth0 OAuth provider."""++ def test_settings_from_env_vars(self):+ """Test that settings can be loaded from environment variables."""+ with patch.dict(+ os.environ,+ {+ "FASTMCP_SERVER_AUTH_AUTH0_CONFIG_URL": TEST_CONFIG_URL,+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID": TEST_CLIENT_ID,+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET": TEST_CLIENT_SECRET,+ "FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE": TEST_AUDIENCE,+ "FASTMCP_SERVER_AUTH_AUTH0_BASE_URL": TEST_BASE_URL,+ "FASTMCP_SERVER_AUTH_AUTH0_REDIRECT_PATH": TEST_REDIRECT_PATH,+ "FASTMCP_SERVER_AUTH_AUTH0_REQUIRED_SCOPES": ",".join(+ TEST_REQUIRED_SCOPES+ ),+ },+ ):+ settings = Auth0ProviderSettings()++ assert str(settings.config_url) == TEST_CONFIG_URL+ assert settings.client_id == TEST_CLIENT_ID+ assert (+ settings.client_secret+ and settings.client_secret.get_secret_value() == TEST_CLIENT_SECRET+ )+ assert settings.audience == TEST_AUDIENCE+ assert str(settings.base_url) == TEST_BASE_URL+ assert settings.redirect_path == TEST_REDIRECT_PATH+ assert settings.required_scopes == TEST_REQUIRED_SCOPES++ def test_settings_explicit_override_env(self):+ """Test that explicit settings override environment variables."""+ with patch.dict(+ os.environ,+ {+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID": TEST_CLIENT_ID,+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET": TEST_CLIENT_SECRET,+ },+ ):+ settings = Auth0ProviderSettings.model_validate(+ {+ "client_id": "explicit_client_id",+ "client_secret": "explicit_secret",+ }+ )++ assert settings.client_id == "explicit_client_id"+ assert (+ settings.client_secret+ and settings.client_secret.get_secret_value() == "explicit_secret"+ )+++class TestAuth0Provider:+ """Test Auth0Provider initialization."""++ def test_init_with_explicit_params(self, valid_oidc_configuration_dict):+ """Test initialization with explicit parameters."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ provider = Auth0Provider(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ audience=TEST_AUDIENCE,+ base_url=TEST_BASE_URL,+ redirect_path=TEST_REDIRECT_PATH,+ required_scopes=TEST_REQUIRED_SCOPES,+ )++ mock_get.assert_called_once()++ call_args = mock_get.call_args+ assert str(call_args[0][0]) == TEST_CONFIG_URL++ assert provider._upstream_client_id == TEST_CLIENT_ID+ assert (+ provider._upstream_client_secret.get_secret_value()+ == TEST_CLIENT_SECRET+ )++ assert isinstance(provider._token_validator, JWTVerifier)+ assert provider._token_validator.audience == TEST_AUDIENCE++ assert str(provider.base_url) == TEST_BASE_URL+ assert provider._redirect_path == TEST_REDIRECT_PATH+ assert provider._token_validator.required_scopes == TEST_REQUIRED_SCOPES++ @pytest.mark.parametrize(+ "scopes_env",+ [+ "openid,email",+ '["openid", "email"]',+ ],+ )+ def test_init_with_env_vars(self, scopes_env, valid_oidc_configuration_dict):+ """Test initialization with environment variables."""+ with (+ patch.dict(+ os.environ,+ {+ "FASTMCP_SERVER_AUTH_AUTH0_CONFIG_URL": TEST_CONFIG_URL,+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID": TEST_CLIENT_ID,+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET": TEST_CLIENT_SECRET,+ "FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE": TEST_AUDIENCE,+ "FASTMCP_SERVER_AUTH_AUTH0_BASE_URL": TEST_BASE_URL,+ "FASTMCP_SERVER_AUTH_AUTH0_REQUIRED_SCOPES": scopes_env,+ },+ ),+ patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get,+ ):+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ provider = Auth0Provider()++ mock_get.assert_called_once()++ call_args = mock_get.call_args+ assert str(call_args[0][0]) == TEST_CONFIG_URL++ assert provider._upstream_client_id == TEST_CLIENT_ID+ assert (+ provider._upstream_client_secret.get_secret_value()+ == TEST_CLIENT_SECRET+ )++ assert isinstance(provider._token_validator, JWTVerifier)+ assert provider._token_validator.audience == TEST_AUDIENCE++ assert str(provider.base_url) == TEST_BASE_URL+ assert provider._token_validator.required_scopes == TEST_REQUIRED_SCOPES++ def test_init_explicit_overrides_env(self, valid_oidc_configuration_dict):+ """Test that explicit parameters override environment variables."""+ with (+ patch.dict(+ os.environ,+ {+ "FASTMCP_SERVER_AUTH_AUTH0_CONFIG_URL": TEST_CONFIG_URL,+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID": TEST_CLIENT_ID,+ "FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET": TEST_CLIENT_SECRET,+ "FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE": TEST_AUDIENCE,+ "FASTMCP_SERVER_AUTH_AUTH0_BASE_URL": TEST_BASE_URL,+ },+ ),+ patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get,+ ):+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ provider = Auth0Provider(+ client_id="explicit_client",+ client_secret="explicit_secret",+ )++ assert provider._upstream_client_id == "explicit_client"+ assert (+ provider._upstream_client_secret.get_secret_value() == "explicit_secret"+ )++ def test_init_missing_config_url_raises_error(self):+ """Test that missing config_url raises ValueError."""+ # Clear environment variables to test proper error handling+ with patch.dict(os.environ, {}, clear=True):+ with pytest.raises(ValueError, match="config_url is required"):+ Auth0Provider()++ def test_init_missing_client_id_raises_error(self):+ """Test that missing client_id raises ValueError."""+ # Clear environment variables to test proper error handling+ with patch.dict(os.environ, {}, clear=True):+ with pytest.raises(ValueError, match="client_id is required"):+ Auth0Provider(config_url=TEST_CONFIG_URL)++ def test_init_missing_client_secret_raises_error(self):+ """Test that missing client_secret raises ValueError."""+ # Clear environment variables to test proper error handling+ with patch.dict(os.environ, {}, clear=True):+ with pytest.raises(ValueError, match="client_secret is required"):+ Auth0Provider(config_url=TEST_CONFIG_URL, client_id=TEST_CLIENT_ID)++ def test_init_missing_audience_raises_error(self):+ """Test that missing audience raises ValueError."""+ # Clear environment variables to test proper error handling+ with patch.dict(os.environ, {}, clear=True):+ with pytest.raises(ValueError, match="audience is required"):+ Auth0Provider(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ )++ def test_init_missing_base_url_raises_error(self):+ """Test that missing base_url raises ValueError."""+ # Clear environment variables to test proper error handling+ with patch.dict(os.environ, {}, clear=True):+ with pytest.raises(ValueError, match="base_url is required"):+ Auth0Provider(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ audience=TEST_AUDIENCE,+ )++ def test_init_defaults(self, valid_oidc_configuration_dict):+ """Test that default values are applied correctly."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ provider = Auth0Provider(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ audience=TEST_AUDIENCE,+ base_url=TEST_BASE_URL,+ )++ # Check defaults+ assert provider._token_validator.required_scopes == ["openid"]diff --git a/tests/server/auth/test_oidc_proxy.py b/tests/server/auth/test_oidc_proxy.pynew file mode 100644index 000000000..5652adbdd--- /dev/null+++ b/tests/server/auth/test_oidc_proxy.py@@ -0,0 +1,392 @@+"""Comprehensive tests for OIDC Proxy Provider functionality."""++from unittest.mock import MagicMock, patch++import pytest+from httpx import Response+from pydantic import AnyHttpUrl++from fastmcp.server.auth.oidc_proxy import OIDCConfiguration, OIDCProxy+from fastmcp.server.auth.providers.jwt import JWTVerifier++TEST_AUTHORIZATION_ENDPOINT = "https://example.com/authorize"+TEST_TOKEN_ENDPOINT = "https://example.com/oauth/token"++TEST_CONFIG_URL = "https://example.com/.well-known/openid-configuration"+TEST_CLIENT_ID = "test-client-id"+TEST_CLIENT_SECRET = "test-client-secret"+TEST_BASE_URL = "https://example.com:8000/"+++# =============================================================================+# Test Fixtures+# =============================================================================+++def valid_oidc_configuration_dict():+ """Create a valid OIDC configuration dict for testing."""+ return {+ "issuer": "https://example.com/",+ "authorization_endpoint": TEST_AUTHORIZATION_ENDPOINT,+ "token_endpoint": TEST_TOKEN_ENDPOINT,+ "jwks_uri": "https://example.com/.well-known/jwks.json",+ "response_types_supported": ["code"],+ "subject_types_supported": ["public"],+ "id_token_signing_alg_values_supported": ["RS256"],+ }+++def invalid_oidc_configuration_dict():+ """Create an invalid OIDC configuration dict for testing."""+ return {+ "issuer": "https://example.com/",+ "authorization_endpoint": TEST_AUTHORIZATION_ENDPOINT,+ "token_endpoint": TEST_TOKEN_ENDPOINT,+ "jwks_uri": "https://example.com/.well-known/jwks.json",+ }+++# =============================================================================+# Test Classes+# =============================================================================+++def validate_config(config):+ """Validate an OIDC configuration."""+ assert str(config.issuer) == "https://example.com/"+ assert str(config.authorization_endpoint) == TEST_AUTHORIZATION_ENDPOINT+ assert str(config.token_endpoint) == TEST_TOKEN_ENDPOINT+ assert str(config.jwks_uri) == "https://example.com/.well-known/jwks.json"+ assert config.response_types_supported == ["code"]+ assert config.subject_types_supported == ["public"]+ assert config.id_token_signing_alg_values_supported == ["RS256"]+++class TestOIDCConfiguration:+ """Tests for OIDC configuration."""++ def test_default_configuration(self, valid_oidc_configuration_dict):+ """Test default configuration with valid dict."""+ config = OIDCConfiguration.model_validate(valid_oidc_configuration_dict)+ validate_config(config)++ def test_explicit_strict_configuration(self, valid_oidc_configuration_dict):+ """Test default configuration with explicit True strict setting and valid dict."""+ valid_oidc_configuration_dict["strict"] = True+ config = OIDCConfiguration.model_validate(valid_oidc_configuration_dict)+ validate_config(config)++ def test_default_configuration_raises_error(self, invalid_oidc_configuration_dict):+ """Test default configuration with invalid dict."""+ with pytest.raises(ValueError, match="Missing required configuration metadata"):+ OIDCConfiguration.model_validate(invalid_oidc_configuration_dict)++ def test_explicit_strict_configuration_raises_error(+ self, invalid_oidc_configuration_dict+ ):+ """Test default configuration with explicit True strict setting and invalid dict."""+ invalid_oidc_configuration_dict["strict"] = True+ with pytest.raises(ValueError, match="Missing required configuration metadata"):+ OIDCConfiguration.model_validate(invalid_oidc_configuration_dict)++ def test_not_strict_configuration(self):+ """Test default configuration with explicit False strict setting."""+ config = OIDCConfiguration.model_validate({"strict": False})++ assert config.issuer is None+ assert config.authorization_endpoint is None+ assert config.token_endpoint is None+ assert config.jwks_uri is None+ assert config.response_types_supported is None+ assert config.subject_types_supported is None+ assert config.id_token_signing_alg_values_supported is None+++def validate_get_oidc_configuration(oidc_configuration, strict, timeout_seconds):+ """Validate get_oidc_configuation call."""+ with patch("httpx.get") as mock_get:+ mock_response = MagicMock(spec=Response)+ mock_response.json.return_value = oidc_configuration+ mock_get.return_value = mock_response++ config = OIDCConfiguration.get_oidc_configuration(+ config_url=AnyHttpUrl(TEST_CONFIG_URL),+ strict=strict,+ timeout_seconds=timeout_seconds,+ )++ validate_config(config)++ mock_get.assert_called_once()++ call_args = mock_get.call_args+ assert call_args[0][0] == TEST_CONFIG_URL++ return call_args+++class TestGetOIDCConfiguration:+ """Tests for getting OIDC configuration."""++ def test_get_oidc_configuration(self, valid_oidc_configuration_dict):+ """Test with valid response and explicit timeout."""+ call_args = validate_get_oidc_configuration(+ valid_oidc_configuration_dict, True, 10+ )+ assert call_args[1]["timeout"] == 10++ def test_get_oidc_configuration_no_timeout(self, valid_oidc_configuration_dict):+ """Test with valid response and no timeout."""+ call_args = validate_get_oidc_configuration(+ valid_oidc_configuration_dict, True, None+ )+ assert "timeout" not in call_args[1]++ def test_get_oidc_configuration_raises_error(+ self, invalid_oidc_configuration_dict+ ) -> None:+ """Test with invalid response."""+ with pytest.raises(ValueError, match="Missing required configuration metadata"):+ validate_get_oidc_configuration(invalid_oidc_configuration_dict, True, 10)++ def test_get_oidc_configuration_not_strict(+ self, invalid_oidc_configuration_dict+ ) -> None:+ """Test with invalid response and strict set to False."""+ with patch("httpx.get") as mock_get:+ mock_response = MagicMock(spec=Response)+ mock_response.json.return_value = invalid_oidc_configuration_dict+ mock_get.return_value = mock_response++ OIDCConfiguration.get_oidc_configuration(+ config_url=AnyHttpUrl(TEST_CONFIG_URL),+ strict=False,+ timeout_seconds=10,+ )++ mock_get.assert_called_once()++ call_args = mock_get.call_args+ assert call_args[0][0] == TEST_CONFIG_URL+++def validate_proxy(mock_get, proxy, oidc_config):+ """Validate OIDC proxy."""+ mock_get.assert_called_once()++ call_args = mock_get.call_args+ assert str(call_args[0][0]) == TEST_CONFIG_URL++ assert proxy._upstream_authorization_endpoint == TEST_AUTHORIZATION_ENDPOINT+ assert proxy._upstream_token_endpoint == TEST_TOKEN_ENDPOINT+ assert proxy._upstream_client_id == TEST_CLIENT_ID+ assert proxy._upstream_client_secret.get_secret_value() == TEST_CLIENT_SECRET+ assert str(proxy.base_url) == TEST_BASE_URL+ assert proxy.oidc_config == oidc_config+++class TestOIDCProxyInitialization:+ """Tests for OIDC proxy initialization."""++ def test_default_initialization(self, valid_oidc_configuration_dict):+ """Test default initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ proxy = OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ base_url=TEST_BASE_URL,+ )++ validate_proxy(mock_get, proxy, oidc_config)++ def test_timeout_seconds_initialization(self, valid_oidc_configuration_dict):+ """Test timeout seconds initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ proxy = OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ base_url=TEST_BASE_URL,+ timeout_seconds=12,+ )++ validate_proxy(mock_get, proxy, oidc_config)++ call_args = mock_get.call_args+ assert call_args[1]["timeout_seconds"] == 12++ def test_token_verifier_initialization(self, valid_oidc_configuration_dict):+ """Test token verifier initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ proxy = OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ base_url=TEST_BASE_URL,+ algorithm="RS256",+ audience="oidc-proxy-test-audience",+ required_scopes=["required", "scopes"],+ )++ validate_proxy(mock_get, proxy, oidc_config)++ assert isinstance(proxy._token_validator, JWTVerifier)++ assert proxy._token_validator.algorithm == "RS256"+ assert proxy._token_validator.audience == "oidc-proxy-test-audience"+ assert proxy._token_validator.required_scopes == ["required", "scopes"]++ def test_extra_parameters_initialization(self, valid_oidc_configuration_dict):+ """Test other parameters initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ proxy = OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ base_url=TEST_BASE_URL,+ audience="oidc-proxy-test-audience",+ )++ validate_proxy(mock_get, proxy, oidc_config)++ assert proxy._extra_authorize_params == {+ "audience": "oidc-proxy-test-audience"+ }+ assert proxy._extra_token_params == {"audience": "oidc-proxy-test-audience"}++ def test_other_parameters_initialization(self, valid_oidc_configuration_dict):+ """Test other parameters initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ proxy = OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ base_url=TEST_BASE_URL,+ redirect_path="/oidc/proxy",+ allowed_client_redirect_uris=["http://localhost:*"],+ token_endpoint_auth_method="client_secret_post",+ )++ validate_proxy(mock_get, proxy, oidc_config)++ assert proxy._redirect_path == "/oidc/proxy"+ assert proxy._allowed_client_redirect_uris == ["http://localhost:*"]+ assert proxy._token_endpoint_auth_method == "client_secret_post"++ def test_no_config_url_initialization_raises_error(+ self, valid_oidc_configuration_dict+ ):+ """Test no config URL initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ with pytest.raises(ValueError, match="Missing required config URL"):+ OIDCProxy(+ config_url=None, # type: ignore+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ base_url=TEST_BASE_URL,+ )++ def test_no_client_id_initialization_raises_error(+ self, valid_oidc_configuration_dict+ ):+ """Test no client id initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ with pytest.raises(ValueError, match="Missing required client id"):+ OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=None, # type: ignore+ client_secret=TEST_CLIENT_SECRET,+ base_url=TEST_BASE_URL,+ )++ def test_no_client_secret_initialization_raises_error(+ self, valid_oidc_configuration_dict+ ):+ """Test no client secret initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ with pytest.raises(ValueError, match="Missing required client secret"):+ OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=None, # type: ignore+ base_url=TEST_BASE_URL,+ )++ def test_no_base_url_initialization_raises_error(+ self, valid_oidc_configuration_dict+ ):+ """Test no base URL initialization."""+ with patch(+ "fastmcp.server.auth.oidc_proxy.OIDCConfiguration.get_oidc_configuration"+ ) as mock_get:+ oidc_config = OIDCConfiguration.model_validate(+ valid_oidc_configuration_dict+ )+ mock_get.return_value = oidc_config++ with pytest.raises(ValueError, match="Missing required base URL"):+ OIDCProxy(+ config_url=TEST_CONFIG_URL,+ client_id=TEST_CLIENT_ID,+ client_secret=TEST_CLIENT_SECRET,+ base_url=None, # type: ignore+ )