π The fast, Pythonic way to build MCP servers and clients.
Add RFC 7662 token introspection provider (#2074)
Jeremiah Lowin52e9af121487
diff --git a/docs/servers/auth/oauth-proxy.mdx b/docs/servers/auth/oauth-proxy.mdxindex c06276e26..47ce45616 100644--- a/docs/servers/auth/oauth-proxy.mdx+++ b/docs/servers/auth/oauth-proxy.mdx@@ -226,7 +226,8 @@ Available providers include `GitHubProvider`, `GoogleProvider`, and others. ThesThe OAuth proxy requires a compatible `TokenVerifier` to validate tokens from your provider. Different providers use different token formats:- **JWT tokens** (Google, Azure): Use `JWTVerifier` with the provider's JWKS endpoint-- **Opaque tokens** (GitHub, Discord): Use provider-specific verifiers or implement custom validation+- **Opaque tokens with RFC 7662 introspection** (Auth0, Okta, WorkOS): Use `IntrospectionTokenVerifier`+- **Opaque tokens (provider-specific)** (GitHub, Discord): Use provider-specific verifiers like `GitHubTokenVerifier`See the [Token Verification guide](/servers/auth/token-verification) for detailed setup instructions for your provider.diff --git a/docs/servers/auth/remote-oauth.mdx b/docs/servers/auth/remote-oauth.mdxindex b01aef315..befb6ec22 100644--- a/docs/servers/auth/remote-oauth.mdx+++ b/docs/servers/auth/remote-oauth.mdx@@ -86,7 +86,12 @@ FastMCP provides `RemoteAuthProvider` to handle the complexities of remote OAuth`RemoteAuthProvider` works by composing a [`TokenVerifier`](/servers/auth/token-verification) with authorization server information. A `TokenVerifier` is another FastMCP authentication class that focuses solely on token validation - signature verification, expiration checking, and claim extraction. The `RemoteAuthProvider` takes that token validation capability and adds the OAuth discovery endpoints that enable MCP clients to automatically find and authenticate with your identity provider.-This composition pattern means you can use any token validation strategy (JWT verification, introspection endpoints, custom validation logic) while maintaining consistent OAuth discovery behavior. The separation allows you to change token validation approaches without affecting the client discovery experience.+This composition pattern means you can use any token validation strategy while maintaining consistent OAuth discovery behavior:+- **JWT tokens**: Use `JWTVerifier` for self-contained tokens+- **Opaque tokens**: Use `IntrospectionTokenVerifier` for RFC 7662 introspection+- **Custom validation**: Implement your own `TokenVerifier` subclass++The separation allows you to change token validation approaches without affecting the client discovery experience.The class automatically generates the required OAuth metadata endpoints using the MCP SDK's standardized route creation functions. This ensures compatibility with MCP clients while reducing the implementation complexity for server developers.diff --git a/docs/servers/auth/token-verification.mdx b/docs/servers/auth/token-verification.mdxindex d2523151c..637ff77a2 100644--- a/docs/servers/auth/token-verification.mdx+++ b/docs/servers/auth/token-verification.mdx@@ -42,11 +42,10 @@ Token validation must address several security requirements: signature verificatThe challenge in MCP environments is that clients need to obtain valid tokens before making requests, but the MCP protocol doesn't provide built-in discovery mechanisms for token endpoints. Clients must obtain tokens through separate channels or prior configuration.-## FastMCP Token Verification-FastMCP provides the `TokenVerifier` class to handle token validation complexity while remaining flexible about token sources and validation strategies.+## TokenVerifier Class-### TokenVerifier Design+FastMCP provides the `TokenVerifier` class to handle token validation complexity while remaining flexible about token sources and validation strategies.`TokenVerifier` focuses exclusively on token validation without providing OAuth discovery metadata. This makes it ideal for internal systems where clients already know how to obtain tokens, or for microservices that trust tokens from known issuers.@@ -54,11 +53,11 @@ The class validates token signatures, checks expiration timestamps, and extractsYou can subclass `TokenVerifier` to implement custom validation logic for specialized token formats or validation requirements. The base class handles common patterns while allowing extension for unique use cases.-### JWT Token Verification+## JWT Token VerificationJSON Web Tokens (JWTs) represent the most common token format for modern applications. FastMCP's `JWTVerifier` validates JWTs using industry-standard cryptographic techniques and claim validation.-#### JWKS Endpoint Integration+### JWKS Endpoint IntegrationJWKS endpoint integration provides the most flexible approach for production systems. The verifier automatically fetches public keys from a JSON Web Key Set endpoint, enabling automatic key rotation without server configuration changes.@@ -80,7 +79,7 @@ This configuration creates a server that validates JWTs issued by `auth.yourcompThe `issuer` parameter ensures tokens come from your trusted authentication system, while `audience` validation prevents tokens intended for other services from being accepted by your MCP server.-#### Symmetric Key Verification (HMAC)+### Symmetric Key Verification (HMAC)Symmetric key verification uses a shared secret for both signing and validation, making it ideal for internal microservices and trusted environments where the same secret can be securely distributed to both token issuers and validators.@@ -119,7 +118,7 @@ The parameter is named `public_key` for backwards compatibility, but when using- Consider using asymmetric keys (RSA/ECDSA) for external-facing APIs</Warning>-#### Static Public Key Verification+### Static Public Key VerificationStatic public key verification works when you have a fixed RSA or ECDSA signing key and don't need automatic key rotation. This approach is primarily useful for development environments or controlled deployments where JWKS endpoints aren't available.@@ -142,12 +141,44 @@ mcp = FastMCP(name="Protected API", auth=verifier)```This configuration validates tokens using a specific RSA or ECDSA public key. The key must correspond to the private key used by your token issuer. While less flexible than JWKS endpoints, this approach can be useful in development environments or when testing with fixed keys.+## Opaque Token Verification++Many authorization servers issue opaque tokens rather than self-contained JWTs. Opaque tokens are random strings that carry no information themselves - the authorization server maintains their state and validation requires querying the server. FastMCP supports opaque token validation through OAuth 2.0 Token Introspection (RFC 7662).++### Understanding Opaque Tokens++Opaque tokens differ fundamentally from JWTs in their verification model. Where JWTs carry signed claims that can be validated locally, opaque tokens require network calls to the issuing authorization server for validation. The authorization server maintains token state and can revoke tokens immediately, providing stronger security guarantees for sensitive operations.++This approach trades performance (network latency on each validation) for security and flexibility. Authorization servers can revoke opaque tokens instantly, implement complex authorization logic, and maintain detailed audit logs of token usage. Many enterprise OAuth providers default to opaque tokens for these security advantages.++### Token Introspection Protocol++RFC 7662 standardizes how resource servers validate opaque tokens. The protocol defines an introspection endpoint where resource servers authenticate using client credentials and receive token metadata including active status, scopes, expiration, and subject identity.++FastMCP implements this protocol through the `IntrospectionTokenVerifier` class, handling authentication, request formatting, and response parsing according to the specification.-### Development and Testing+```python+from fastmcp import FastMCP+from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier++# Configure introspection with your OAuth provider+verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.yourcompany.com/oauth/introspect",+ client_id="mcp-resource-server",+ client_secret="your-client-secret",+ required_scopes=["api:read", "api:write"]+)++mcp = FastMCP(name="Protected API", auth=verifier)+```++The verifier authenticates to the introspection endpoint using HTTP Basic Auth with your client credentials. When a request arrives with a bearer token, FastMCP queries the introspection endpoint to determine if the token is active and has sufficient scopes.++## Development and TestingDevelopment environments often need simpler token management without the complexity of full JWT infrastructure. FastMCP provides tools specifically designed for these scenarios.-#### Static Token Verification+### Static Token VerificationStatic token verification enables rapid development by accepting predefined tokens with associated claims. This approach eliminates the need for token generation infrastructure during development and testing.@@ -179,7 +210,8 @@ Clients can now authenticate using `Authorization: Bearer dev-alice-token` headeStatic token verification stores tokens as plain text and should never be used in production environments. It's designed exclusively for development and testing scenarios.</Warning>-#### Test Token Generation++### Test Token GenerationTest token generation helps when you need to test JWT verification without setting up complete identity infrastructure. FastMCP includes utilities for generating test key pairs and signed tokens.diff --git a/src/fastmcp/server/auth/providers/introspection.py b/src/fastmcp/server/auth/providers/introspection.pynew file mode 100644index 000000000..c9e865bd9--- /dev/null+++ b/src/fastmcp/server/auth/providers/introspection.py@@ -0,0 +1,281 @@+"""OAuth 2.0 Token Introspection (RFC 7662) provider for FastMCP.++This module provides token verification for opaque tokens using the OAuth 2.0+Token Introspection protocol defined in RFC 7662. It allows FastMCP servers to+validate tokens issued by authorization servers that don't use JWT format.++Example:+ ```python+ from fastmcp import FastMCP+ from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier++ # Verify opaque tokens via RFC 7662 introspection+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="your-client-id",+ client_secret="your-client-secret",+ required_scopes=["read", "write"]+ )++ mcp = FastMCP("My Protected Server", auth=verifier)+ ```+"""++from __future__ import annotations++import base64+import time+from typing import Any++import httpx+from pydantic import AnyHttpUrl, SecretStr, field_validator+from pydantic_settings import BaseSettings, SettingsConfigDict++from fastmcp.server.auth import AccessToken, TokenVerifier+from fastmcp.settings import ENV_FILE+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 IntrospectionTokenVerifierSettings(BaseSettings):+ """Settings for OAuth 2.0 Token Introspection verification."""++ model_config = SettingsConfigDict(+ env_prefix="FASTMCP_SERVER_AUTH_INTROSPECTION_",+ env_file=ENV_FILE,+ extra="ignore",+ )++ introspection_url: str | None = None+ client_id: str | None = None+ client_secret: SecretStr | None = None+ timeout_seconds: int = 10+ required_scopes: list[str] | None = None+ base_url: AnyHttpUrl | str | None = None++ @field_validator("required_scopes", mode="before")+ @classmethod+ def _parse_scopes(cls, v):+ return parse_scopes(v)+++class IntrospectionTokenVerifier(TokenVerifier):+ """+ OAuth 2.0 Token Introspection verifier (RFC 7662).++ This verifier validates opaque tokens by calling an OAuth 2.0 token introspection+ endpoint. Unlike JWT verification which is stateless, token introspection requires+ a network call to the authorization server for each token validation.++ The verifier authenticates to the introspection endpoint using HTTP Basic Auth+ with the provided client_id and client_secret, as specified in RFC 7662.++ Use this when:+ - Your authorization server issues opaque (non-JWT) tokens+ - You need to validate tokens from Auth0, Okta, Keycloak, or other OAuth servers+ - Your tokens require real-time revocation checking+ - Your authorization server supports RFC 7662 introspection++ Example:+ ```python+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="my-service",+ client_secret="secret-key",+ required_scopes=["api:read"]+ )+ ```+ """++ def __init__(+ self,+ *,+ introspection_url: str | NotSetT = NotSet,+ client_id: str | NotSetT = NotSet,+ client_secret: str | NotSetT = NotSet,+ timeout_seconds: int | NotSetT = NotSet,+ required_scopes: list[str] | None | NotSetT = NotSet,+ base_url: AnyHttpUrl | str | None | NotSetT = NotSet,+ ):+ """+ Initialize the introspection token verifier.++ Args:+ introspection_url: URL of the OAuth 2.0 token introspection endpoint+ client_id: OAuth client ID for authenticating to the introspection endpoint+ client_secret: OAuth client secret for authenticating to the introspection endpoint+ timeout_seconds: HTTP request timeout in seconds (default: 10)+ required_scopes: Required scopes for all tokens (optional)+ base_url: Base URL for TokenVerifier protocol+ """+ settings = IntrospectionTokenVerifierSettings.model_validate(+ {+ k: v+ for k, v in {+ "introspection_url": introspection_url,+ "client_id": client_id,+ "client_secret": client_secret,+ "timeout_seconds": timeout_seconds,+ "required_scopes": required_scopes,+ "base_url": base_url,+ }.items()+ if v is not NotSet+ }+ )++ if not settings.introspection_url:+ raise ValueError(+ "introspection_url is required - set via parameter or "+ "FASTMCP_SERVER_AUTH_INTROSPECTION_INTROSPECTION_URL"+ )+ if not settings.client_id:+ raise ValueError(+ "client_id is required - set via parameter or "+ "FASTMCP_SERVER_AUTH_INTROSPECTION_CLIENT_ID"+ )+ if not settings.client_secret:+ raise ValueError(+ "client_secret is required - set via parameter or "+ "FASTMCP_SERVER_AUTH_INTROSPECTION_CLIENT_SECRET"+ )++ super().__init__(+ base_url=settings.base_url, required_scopes=settings.required_scopes+ )++ self.introspection_url = settings.introspection_url+ self.client_id = settings.client_id+ self.client_secret = settings.client_secret.get_secret_value()+ self.timeout_seconds = settings.timeout_seconds+ self.logger = get_logger(__name__)++ def _create_basic_auth_header(self) -> str:+ """Create HTTP Basic Auth header value from client credentials."""+ credentials = f"{self.client_id}:{self.client_secret}"+ encoded = base64.b64encode(credentials.encode("utf-8")).decode("utf-8")+ return f"Basic {encoded}"++ def _extract_scopes(self, introspection_response: dict[str, Any]) -> list[str]:+ """+ Extract scopes from introspection response.++ RFC 7662 allows scopes to be returned as either:+ - A space-separated string in the 'scope' field+ - An array of strings in the 'scope' field (less common but valid)+ """+ scope_value = introspection_response.get("scope")++ if scope_value is None:+ return []++ # Handle string (space-separated) scopes+ if isinstance(scope_value, str):+ return [s.strip() for s in scope_value.split() if s.strip()]++ # Handle array of scopes+ if isinstance(scope_value, list):+ return [str(s) for s in scope_value if s]++ return []++ async def verify_token(self, token: str) -> AccessToken | None:+ """+ Verify a bearer token using OAuth 2.0 Token Introspection (RFC 7662).++ This method makes a POST request to the introspection endpoint with the token,+ authenticated using HTTP Basic Auth with the client credentials.++ Args:+ token: The opaque token string to validate++ Returns:+ AccessToken object if valid and active, None if invalid, inactive, or expired+ """+ try:+ async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:+ # Prepare introspection request per RFC 7662+ auth_header = self._create_basic_auth_header()++ response = await client.post(+ self.introspection_url,+ data={+ "token": token,+ "token_type_hint": "access_token",+ },+ headers={+ "Authorization": auth_header,+ "Content-Type": "application/x-www-form-urlencoded",+ "Accept": "application/json",+ },+ )++ # Check for HTTP errors+ if response.status_code != 200:+ self.logger.debug(+ "Token introspection failed: HTTP %d - %s",+ response.status_code,+ response.text[:200] if response.text else "",+ )+ return None++ introspection_data = response.json()++ # Check if token is active (required field per RFC 7662)+ if not introspection_data.get("active", False):+ self.logger.debug("Token introspection returned active=false")+ return None++ # Extract client_id (should be present for active tokens)+ client_id = introspection_data.get(+ "client_id"+ ) or introspection_data.get("sub", "unknown")++ # Extract expiration time+ exp = introspection_data.get("exp")+ if exp:+ # Validate expiration (belt and suspenders - server should set active=false)+ if exp < time.time():+ self.logger.debug(+ "Token validation failed: expired token for client %s",+ client_id,+ )+ return None++ # Extract scopes+ scopes = self._extract_scopes(introspection_data)++ # Check required scopes+ if self.required_scopes:+ token_scopes = set(scopes)+ required_scopes = set(self.required_scopes)+ if not required_scopes.issubset(token_scopes):+ self.logger.debug(+ "Token missing required scopes. Has: %s, Required: %s",+ token_scopes,+ required_scopes,+ )+ return None++ # Create AccessToken with introspection response data+ return AccessToken(+ token=token,+ client_id=str(client_id),+ scopes=scopes,+ expires_at=int(exp) if exp else None,+ claims=introspection_data, # Store full response for extensibility+ )++ except httpx.TimeoutException:+ self.logger.debug(+ "Token introspection timed out after %d seconds", self.timeout_seconds+ )+ return None+ except httpx.RequestError as e:+ self.logger.debug("Token introspection request failed: %s", e)+ return None+ except Exception as e:+ self.logger.debug("Token introspection error: %s", e)+ return Nonediff --git a/tests/client/test_openapi_experimental.py b/tests/client/test_openapi_experimental.pyindex 6e32024b3..c4b0636a9 100644--- a/tests/client/test_openapi_experimental.py+++ b/tests/client/test_openapi_experimental.py@@ -191,6 +191,7 @@ async def test_client_with_excluded_header_is_ignored(sse_server: str):assert headers["host"] == "fastapi"[email protected](retries=2, delay=1)async def test_client_headers_proxy(proxy_server: str):"""Test that client headers are passed through the proxy to the remove server.diff --git a/tests/server/auth/providers/test_introspection.py b/tests/server/auth/providers/test_introspection.pynew file mode 100644index 000000000..c60bef9d1--- /dev/null+++ b/tests/server/auth/providers/test_introspection.py@@ -0,0 +1,463 @@+"""Tests for OAuth 2.0 Token Introspection verifier (RFC 7662)."""++import base64+import time+from typing import Any++import pytest+from pydantic import SecretStr+from pytest_httpx import HTTPXMock++from fastmcp.server.auth.providers.introspection import (+ IntrospectionTokenVerifier,+ IntrospectionTokenVerifierSettings,+)+++class TestIntrospectionTokenVerifierSettings:+ """Test settings loading and validation."""++ def test_settings_from_parameters(self):+ """Test creating settings from parameters."""+ settings = IntrospectionTokenVerifierSettings(+ introspection_url="https://auth.example.com/introspect",+ client_id="test-client",+ client_secret=SecretStr("test-secret"),+ timeout_seconds=5,+ required_scopes=["read", "write"],+ )++ assert settings.introspection_url == "https://auth.example.com/introspect"+ assert settings.client_id == "test-client"+ assert settings.client_secret+ assert settings.client_secret.get_secret_value() == "test-secret"+ assert settings.timeout_seconds == 5+ assert settings.required_scopes == ["read", "write"]++ def test_settings_default_timeout(self):+ """Test default timeout value."""+ settings = IntrospectionTokenVerifierSettings(+ introspection_url="https://auth.example.com/introspect",+ client_id="test-client",+ client_secret=SecretStr("test-secret"),+ )++ assert settings.timeout_seconds == 10++ def test_settings_parse_scopes_from_string(self):+ """Test scope parsing from comma-separated string."""+ settings = IntrospectionTokenVerifierSettings(+ introspection_url="https://auth.example.com/introspect",+ client_id="test-client",+ client_secret=SecretStr("test-secret"),+ required_scopes="read,write,admin", # type: ignore+ )++ assert settings.required_scopes == ["read", "write", "admin"]+++class TestIntrospectionTokenVerifier:+ """Test core token verification logic."""++ @pytest.fixture+ def verifier(self) -> IntrospectionTokenVerifier:+ """Create a basic introspection verifier for testing."""+ return IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ timeout_seconds=5,+ )++ @pytest.fixture+ def verifier_with_required_scopes(self) -> IntrospectionTokenVerifier:+ """Create verifier with required scopes."""+ return IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ required_scopes=["read", "write"],+ )++ def test_initialization(self):+ """Test verifier initialization."""+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ )++ assert verifier.introspection_url == "https://auth.example.com/oauth/introspect"+ assert verifier.client_id == "test-client"+ assert verifier.client_secret == "test-secret"+ assert verifier.timeout_seconds == 10++ def test_initialization_requires_introspection_url(self):+ """Test that introspection_url is required."""+ with pytest.raises(ValueError, match="introspection_url is required"):+ IntrospectionTokenVerifier(+ client_id="test-client",+ client_secret="test-secret",+ )++ def test_initialization_requires_client_id(self):+ """Test that client_id is required."""+ with pytest.raises(ValueError, match="client_id is required"):+ IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_secret="test-secret",+ )++ def test_initialization_requires_client_secret(self):+ """Test that client_secret is required."""+ with pytest.raises(ValueError, match="client_secret is required"):+ IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ )++ def test_create_basic_auth_header(self, verifier: IntrospectionTokenVerifier):+ """Test HTTP Basic Auth header creation."""+ auth_header = verifier._create_basic_auth_header()++ # Decode and verify+ assert auth_header.startswith("Basic ")+ encoded = auth_header[6:]+ decoded = base64.b64decode(encoded).decode("utf-8")+ assert decoded == "test-client:test-secret"++ def test_extract_scopes_from_string(self, verifier: IntrospectionTokenVerifier):+ """Test scope extraction from space-separated string."""+ response = {"scope": "read write admin"}+ scopes = verifier._extract_scopes(response)++ assert scopes == ["read", "write", "admin"]++ def test_extract_scopes_from_array(self, verifier: IntrospectionTokenVerifier):+ """Test scope extraction from array."""+ response = {"scope": ["read", "write", "admin"]}+ scopes = verifier._extract_scopes(response)++ assert scopes == ["read", "write", "admin"]++ def test_extract_scopes_missing(self, verifier: IntrospectionTokenVerifier):+ """Test scope extraction when scope field is missing."""+ response: dict[str, Any] = {}+ scopes = verifier._extract_scopes(response)++ assert scopes == []++ def test_extract_scopes_with_extra_whitespace(+ self, verifier: IntrospectionTokenVerifier+ ):+ """Test scope extraction handles extra whitespace."""+ response = {"scope": " read write admin "}+ scopes = verifier._extract_scopes(response)++ assert scopes == ["read", "write", "admin"]++ async def test_valid_token_verification(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test successful token verification."""+ # Mock introspection endpoint+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read write",+ "exp": int(time.time()) + 3600,+ "iat": int(time.time()),+ "sub": "user-123",+ "username": "testuser",+ },+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is not None+ assert access_token.client_id == "user-123"+ assert access_token.scopes == ["read", "write"]+ assert access_token.expires_at is not None+ assert access_token.claims["active"] is True+ assert access_token.claims["username"] == "testuser"++ async def test_inactive_token_returns_none(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that inactive tokens return None."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": False},+ )++ access_token = await verifier.verify_token("expired-token")++ assert access_token is None++ async def test_expired_token_returns_none(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that expired tokens return None."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read",+ "exp": int(time.time()) - 3600, # Expired 1 hour ago+ },+ )++ access_token = await verifier.verify_token("expired-token")++ assert access_token is None++ async def test_token_without_expiration(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test token without expiration field."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read",+ },+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is not None+ assert access_token.expires_at is None++ async def test_token_without_scopes(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test token without scope field."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ },+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is not None+ assert access_token.scopes == []++ async def test_required_scopes_validation(+ self,+ verifier_with_required_scopes: IntrospectionTokenVerifier,+ httpx_mock: HTTPXMock,+ ):+ """Test that required scopes are validated."""+ # Token with insufficient scopes+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read", # Missing 'write'+ },+ )++ access_token = await verifier_with_required_scopes.verify_token("test-token")++ assert access_token is None++ async def test_required_scopes_validation_success(+ self,+ verifier_with_required_scopes: IntrospectionTokenVerifier,+ httpx_mock: HTTPXMock,+ ):+ """Test successful validation with required scopes."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "client_id": "user-123",+ "scope": "read write admin", # Has all required scopes+ },+ )++ access_token = await verifier_with_required_scopes.verify_token("test-token")++ assert access_token is not None+ assert set(access_token.scopes) >= {"read", "write"}++ async def test_http_error_returns_none(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that HTTP errors return None."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ status_code=500,+ text="Internal Server Error",+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is None++ async def test_authentication_failure_returns_none(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that authentication failures return None."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ status_code=401,+ text="Unauthorized",+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is None++ async def test_timeout_returns_none(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that timeouts return None."""+ from httpx import TimeoutException++ httpx_mock.add_exception(+ TimeoutException("Request timed out"),+ url="https://auth.example.com/oauth/introspect",+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is None++ async def test_malformed_json_returns_none(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that malformed JSON responses return None."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ status_code=200,+ text="not json",+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is None++ async def test_request_includes_correct_headers(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that the request includes correct headers and auth."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )++ await verifier.verify_token("test-token")++ # Verify request was made with correct parameters+ request = httpx_mock.get_request()+ assert request is not None+ assert request.method == "POST"+ assert "Authorization" in request.headers+ assert request.headers["Authorization"].startswith("Basic ")+ assert request.headers["Content-Type"] == "application/x-www-form-urlencoded"+ assert request.headers["Accept"] == "application/json"++ async def test_request_includes_token_and_hint(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that the request includes token and token_type_hint."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={"active": True, "client_id": "user-123"},+ )++ await verifier.verify_token("my-test-token")++ request = httpx_mock.get_request()+ assert request is not None++ # Parse form data+ body = request.content.decode("utf-8")+ assert "token=my-test-token" in body+ assert "token_type_hint=access_token" in body++ async def test_client_id_fallback_to_sub(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that client_id falls back to sub if not present."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "sub": "user-456",+ "scope": "read",+ },+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is not None+ assert access_token.client_id == "user-456"++ async def test_client_id_defaults_to_unknown(+ self, verifier: IntrospectionTokenVerifier, httpx_mock: HTTPXMock+ ):+ """Test that client_id defaults to 'unknown' if neither client_id nor sub present."""+ httpx_mock.add_response(+ url="https://auth.example.com/oauth/introspect",+ method="POST",+ json={+ "active": True,+ "scope": "read",+ },+ )++ access_token = await verifier.verify_token("test-token")++ assert access_token is not None+ assert access_token.client_id == "unknown"+++class TestIntrospectionTokenVerifierIntegration:+ """Integration tests with FastMCP server."""++ async def test_verifier_used_by_fastmcp(self):+ """Test that IntrospectionTokenVerifier can be used as FastMCP auth."""+ from fastmcp import FastMCP++ # Create verifier+ verifier = IntrospectionTokenVerifier(+ introspection_url="https://auth.example.com/oauth/introspect",+ client_id="test-client",+ client_secret="test-secret",+ )++ # Create protected server - should work without errors+ mcp = FastMCP("Test Server", auth=verifier)++ @mcp.tool()+ def greet(name: str) -> str:+ """Greet someone."""+ return f"Hello, {name}!"++ # Verify the auth is set correctly+ assert mcp.auth is verifier+ tools = await mcp.get_tools()+ assert len(list(tools)) == 1diff --git a/tests/server/auth/test_oauth_consent_flow.py b/tests/server/auth/test_oauth_consent_flow.pyindex 41eff87ca..45d3cdb34 100644--- a/tests/server/auth/test_oauth_consent_flow.py+++ b/tests/server/auth/test_oauth_consent_flow.py@@ -231,10 +231,12 @@ class TestServerSideStorage:csrf_token = secrets.token_urlsafe(32)# Approve consent with CSRF token+ # Set cookies on client instance to avoid deprecation warning+ for k, v in consent_response.cookies.items():+ test_client.cookies.set(k, v)approval_response = test_client.post("/consent",data={"action": "approve", "txn": txn_id, "csrf_token": csrf_token},- cookies=consent_response.cookies,follow_redirects=False,)