🚀 The fast, Pythonic way to build MCP servers and clients.
feat(auth): add TokenCache support to GoogleTokenVerifier and GoogleProvider (#5366)
Jérôme Viveret285ec7a3463c
diff --git a/docs/integrations/google.mdx b/docs/integrations/google.mdxindex 141444080..f8d471bc6 100644--- a/docs/integrations/google.mdx+++ b/docs/integrations/google.mdx@@ -102,6 +102,29 @@ async def get_user_info() -> dict:}```+### Token Verification Caching++By default, every token verification queries Google. For servers receiving repeated requests with the same token, enable an in-memory cache to reduce network calls and latency:++```python+from fastmcp import FastMCP+from fastmcp.server.auth.providers.google import GoogleProvider++auth_provider = GoogleProvider(+ client_id="123456789.apps.googleusercontent.com",+ client_secret="GOCSPX-abc123...",+ base_url="http://localhost:8000",+ cache_ttl_seconds=300,+ max_cache_size=10_000,+)++mcp = FastMCP(name="Google Secured App", auth=auth_provider)+```++`cache_ttl_seconds` defaults to `None`, which disables caching; `0` also disables it. When enabled, successful verification results remain cached for at most this duration or until the token expires, whichever comes first. Failed verifications are not cached. `max_cache_size` defaults to 10,000 entries; setting it to `0` disables caching. Negative values for either parameter raise `ValueError`. The cache belongs to each provider instance and is cleared when the server restarts. The same parameters are available on `GoogleTokenVerifier` when using it directly.++Choose a TTL appropriate for how quickly your server needs to notice token revocation or changes to Google's user profile data: cached results skip Google's endpoints until the entry expires.+## Testing### Running the Serverdiff --git a/fastmcp_slim/fastmcp/server/auth/providers/google.py b/fastmcp_slim/fastmcp/server/auth/providers/google.pyindex f2cc12c75..4b5ea2037 100644--- a/fastmcp_slim/fastmcp/server/auth/providers/google.py+++ b/fastmcp_slim/fastmcp/server/auth/providers/google.py@@ -34,6 +34,7 @@ from fastmcp.server.auth.auth import AccessTokenfrom fastmcp.server.auth.oauth_proxy import OAuthProxyfrom fastmcp.utilities.auth import parse_scopesfrom fastmcp.utilities.logging import get_logger+from fastmcp.utilities.token_cache import TokenCachelogger = get_logger(__name__)@@ -62,6 +63,10 @@ class GoogleTokenVerifier(TokenVerifier):This returns the OAuth app ID (``aud``), granted scopes, and expiry time.User profile data (name, picture, etc.) is fetched separately from thev2 userinfo endpoint when the token is valid.++ Caching is disabled by default. Set ``cache_ttl_seconds`` to a positive+ integer to cache successful verification results and avoid repeated+ Google API calls for the same token."""def __init__(@@ -69,6 +74,8 @@ class GoogleTokenVerifier(TokenVerifier):*,required_scopes: list[str] | None = None,timeout_seconds: int = 10,+ cache_ttl_seconds: int | None = None,+ max_cache_size: int | None = None,http_client: httpx2.AsyncClient | None = None,audience: str | list[str] | None = None,):@@ -77,6 +84,10 @@ class GoogleTokenVerifier(TokenVerifier):Args:required_scopes: Required OAuth scopes (e.g., ['openid', 'https://www.googleapis.com/auth/userinfo.email'])timeout_seconds: HTTP request timeout+ cache_ttl_seconds: How long to cache verification results in seconds.+ Caching is disabled by default (None). Set to a positive integer+ to enable (e.g., 300 for 5 minutes).+ max_cache_size: Maximum number of tokens to cache. Default: 10 000.http_client: Optional httpx2.AsyncClient for connection pooling. When provided,the client is reused across calls and the caller is responsible for itslifecycle. When None (default), a fresh client is created per call.@@ -96,6 +107,10 @@ class GoogleTokenVerifier(TokenVerifier):self.timeout_seconds = timeout_secondsself._http_client = http_clientself.audience = audience+ self._cache = TokenCache(+ ttl_seconds=cache_ttl_seconds,+ max_size=max_cache_size,+ )async def verify_token(self, token: str) -> AccessToken | None:"""Verify a Google OAuth token using the tokeninfo endpoint.@@ -105,6 +120,10 @@ class GoogleTokenVerifier(TokenVerifier):scopes, and expiry time. On success, fetches user profile data fromthe v2 userinfo endpoint to populate name, picture, and locale claims."""+ is_cached, cached_result = self._cache.get(token)+ if is_cached:+ logger.debug("Google token cache hit")+ return cached_resulttry:async with (contextlib.nullcontext(self._http_client)@@ -213,6 +232,7 @@ class GoogleTokenVerifier(TokenVerifier):"google_user_data": user_data or None,},)+ self._cache.set(token, access_token)logger.debug("Google token verified successfully")return access_token@@ -264,6 +284,8 @@ class GoogleProvider(OAuthProxy):required_scopes: list[str] | None = None,valid_scopes: list[str] | None = None,timeout_seconds: int = 10,+ cache_ttl_seconds: int | None = None,+ max_cache_size: int | None = None,allowed_client_redirect_uris: list[str] | None = None,client_storage: AsyncKeyValue | None = None,jwt_signing_key: str | bytes | None = None,@@ -301,6 +323,10 @@ class GoogleProvider(OAuthProxy):when you want clients to be able to request additional scopes beyond therequired minimum. Shorthands are normalized to full URI forms.timeout_seconds: HTTP request timeout for Google API calls (defaults to 10)+ cache_ttl_seconds: How long to cache token verification results in seconds.+ Caching is disabled by default (None). Set to a positive integer+ to enable (e.g., 300 for 5 minutes).+ max_cache_size: Maximum number of tokens to cache. Default: 10 000.allowed_client_redirect_uris: List of allowed redirect URI patterns for MCP clients.If None (default), all URIs are allowed. If empty list, no URIs are allowed.client_storage: Storage backend for OAuth state (client registrations, encrypted tokens).@@ -359,6 +385,8 @@ class GoogleProvider(OAuthProxy):token_verifier = GoogleTokenVerifier(required_scopes=required_scopes_final,timeout_seconds=timeout_seconds,+ cache_ttl_seconds=cache_ttl_seconds,+ max_cache_size=max_cache_size,http_client=http_client,audience=client_id,)diff --git a/tests/server/auth/providers/test_google.py b/tests/server/auth/providers/test_google.pyindex 36a00ccb7..fdb292bfd 100644--- a/tests/server/auth/providers/test_google.py+++ b/tests/server/auth/providers/test_google.py@@ -607,3 +607,123 @@ class TestGoogleTokenVerifier:assert result is not Noneassert "https://www.googleapis.com/auth/calendar" in result.scopes++ def test_cache_disabled_by_default(self):+ """Caching is disabled by default."""+ verifier = GoogleTokenVerifier()+ assert not verifier._cache.enabled++ def test_cache_enabled_with_ttl(self):+ """Providing cache_ttl_seconds enables the internal TokenCache."""+ verifier = GoogleTokenVerifier(cache_ttl_seconds=300)+ assert verifier._cache.enabled++ async def test_cache_hit_avoids_second_api_call(self, httpx_mock: HTTPXMock):+ """A second verify_token call with the same token uses cache."""+ httpx_mock.add_response(+ url=_TOKENINFO_RE,+ json={+ "aud": "123.apps.googleusercontent.com",+ "sub": "12345",+ "scope": "openid",+ "expires_in": "3600",+ },+ )+ httpx_mock.add_response(+ url=_USERINFO_RE,+ json={"sub": "12345"},+ )++ verifier = GoogleTokenVerifier(cache_ttl_seconds=300)+ result1 = await verifier.verify_token("tok-1")+ assert result1 is not None++ # Second call - should hit cache and not make more HTTP requests+ result2 = await verifier.verify_token("tok-1")+ assert result2 is not None+ assert result2.client_id == result1.client_id++ requests = httpx_mock.get_requests()+ assert len(requests) == 2 # exactly 1 tokeninfo + 1 userinfo call++ async def test_cache_disabled_makes_every_call(self, httpx_mock: HTTPXMock):+ """When cache is disabled (default), every call queries Google endpoints."""+ httpx_mock.add_response(+ url=_TOKENINFO_RE,+ json={+ "aud": "123.apps.googleusercontent.com",+ "sub": "12345",+ "scope": "openid",+ "expires_in": "3600",+ },+ )+ httpx_mock.add_response(+ url=_USERINFO_RE,+ json={"sub": "12345"},+ )+ httpx_mock.add_response(+ url=_TOKENINFO_RE,+ json={+ "aud": "123.apps.googleusercontent.com",+ "sub": "12345",+ "scope": "openid",+ "expires_in": "3600",+ },+ )+ httpx_mock.add_response(+ url=_USERINFO_RE,+ json={"sub": "12345"},+ )++ verifier = GoogleTokenVerifier(cache_ttl_seconds=0)+ await verifier.verify_token("tok-1")+ await verifier.verify_token("tok-1")++ requests = httpx_mock.get_requests()+ assert len(requests) == 4++ async def test_failures_are_not_cached(self, httpx_mock: HTTPXMock):+ """Failed verifications must not be cached."""+ httpx_mock.add_response(+ url=_TOKENINFO_RE,+ status_code=400,+ json={"error": "invalid_token"},+ )+ httpx_mock.add_response(+ url=_TOKENINFO_RE,+ json={+ "aud": "123.apps.googleusercontent.com",+ "sub": "12345",+ "scope": "openid",+ "expires_in": "3600",+ },+ )+ httpx_mock.add_response(+ url=_USERINFO_RE,+ json={"sub": "12345"},+ )++ verifier = GoogleTokenVerifier(cache_ttl_seconds=300)+ result_fail = await verifier.verify_token("tok-retry")+ assert result_fail is None++ result_ok = await verifier.verify_token("tok-retry")+ assert result_ok is not None++ def test_provider_passes_cache_params_to_verifier(+ self, memory_storage: MemoryStore+ ):+ """GoogleProvider correctly propagates cache_ttl_seconds and max_cache_size."""+ provider = GoogleProvider(+ client_id="123.apps.googleusercontent.com",+ base_url="https://myserver.com",+ jwt_signing_key="test-secret",+ client_storage=memory_storage,+ cache_ttl_seconds=120,+ max_cache_size=500,+ )+ verifier = provider._token_validator+ assert isinstance(verifier, GoogleTokenVerifier)+ assert verifier._cache.enabled+ assert verifier._cache._ttl == 120+ assert verifier._cache._max_size == 500