Skip to content

OAuthProxy maps temporarily_unavailable and unexpected refresh failures to invalid_grant and reflects exception details #5002

Closed

Description

@janbernloehr

What happened?

When an OAuthProxy has valid refresh-token state but the upstream OAuth provider rejects a refresh with the standard temporarily_unavailable error, FastMCP returns a TokenError with error="invalid_grant".

The client-facing error_description also contains the upstream provider's raw error description. The same behavior occurs for transport exceptions and unexpected local exceptions such as RuntimeError: they are all converted to invalid_grant, and their exception text is included in the resulting description.

Actual result from the example below:

invalid_grant
Upstream refresh failed: temporarily_unavailable: private-upstream-detail

Expected behavior:

  • Only a definitive refresh-credential rejection should be returned as invalid_grant.
  • A standard temporarily_unavailable response should remain distinguishable from an invalid credential so clients do not discard otherwise valid refresh credentials.
  • Unexpected local exceptions should remain internal server failures rather than being represented as OAuth credential failures.
  • Client-facing responses should not contain raw upstream or internal exception details.

This reproduces on FastMCP 4.0.1, the latest published release. The same catch-all behavior remains on main at commit 75d50ffb683ba502e86bf833411c46234749270b.

This is distinct from #2461: no token or JTI mapping is missing in this reproduction. All local refresh state is present and valid; only the upstream refresh attempt fails temporarily.

Example Code

import asyncio
import time

from fastmcp.server.auth import AccessToken, OAuthProxy, TokenVerifier
from fastmcp.server.auth.oauth_proxy.models import (
    JTIMapping,
    UpstreamTokenSet,
)
from fastmcp.server.auth.oauth_proxy.upstream import OAuthError
from key_value.aio.stores.memory import MemoryStore
from mcp.server.auth.provider import RefreshToken, TokenError
from mcp.shared.auth import OAuthClientInformationFull


class UnusedVerifier(TokenVerifier):
    async def verify_token(self, token: str) -> AccessToken | None:
        return None


class FailingOAuthClient:
    async def refresh_token(
        self,
        *args: object,
        **kwargs: object,
    ) -> dict[str, object]:
        raise OAuthError(
            error="temporarily_unavailable",
            description="private-upstream-detail",
        )

    async def aclose(self) -> None:
        pass


class ReproProxy(OAuthProxy):
    def _create_upstream_oauth_client(self) -> FailingOAuthClient:
        return FailingOAuthClient()


async def main() -> None:
    proxy = ReproProxy(
        upstream_authorization_endpoint="https://idp.example/authorize",
        upstream_token_endpoint="https://idp.example/token",
        upstream_client_id="upstream-client",
        token_verifier=UnusedVerifier(),
        base_url="https://mcp.example",
        client_storage=MemoryStore(),
        jwt_signing_key="0123456789abcdef0123456789abcdef",
    )
    proxy.get_routes("/mcp")

    client = OAuthClientInformationFull(
        client_id="mcp-client",
        redirect_uris=["http://localhost/callback"],
        token_endpoint_auth_method="none",
    )
    refresh_jti = "refresh-jti"
    upstream_token_id = "upstream-token-id"

    refresh_value = proxy.jwt_issuer.issue_refresh_token(
        client_id=client.client_id,
        scopes=["read"],
        jti=refresh_jti,
        expires_in=3600,
    )

    # Seed a complete, valid mapping to isolate the upstream failure behavior.
    await proxy._jti_mapping_store.put(
        key=refresh_jti,
        value=JTIMapping(
            jti=refresh_jti,
            upstream_token_id=upstream_token_id,
            created_at=time.time(),
        ),
        ttl=3600,
    )
    await proxy._upstream_token_store.put(
        key=upstream_token_id,
        value=UpstreamTokenSet(
            upstream_token_id=upstream_token_id,
            access_token="old-access-token",
            refresh_token="old-refresh-token",
            refresh_token_expires_at=time.time() + 3600,
            expires_at=time.time() - 1,
            token_type="Bearer",
            scope="read",
            client_id=client.client_id,
            created_at=time.time(),
        ),
        ttl=3600,
    )

    try:
        await proxy.exchange_refresh_token(
            client,
            RefreshToken(
                token=refresh_value,
                client_id=client.client_id,
                scopes=["read"],
                expires_at=int(time.time()) + 3600,
            ),
            ["read"],
        )
    except TokenError as exc:
        print(exc.error)
        print(exc.error_description)


if __name__ == "__main__":
    asyncio.run(main())

Version Information

FastMCP: 4.0.1
MCP: 2.1.1
httpx2: 2.12.0
Python: 3.14.3
Platform: macOS 26.6.1, arm64

FastMCP main checked at:
75d50ffb683ba502e86bf833411c46234749270b

Activity

  1. added
    bug
    on Sep 4, 2026
  2. added
    auth
    on Sep 4, 2026
  3. feiiiiii5 commented on Sep 6, 2026

    @feiiiiii5
    Contributor

    Confirmed all three failure modes on current main (e3fb4af3) using the MRE shape from this issue: temporarily_unavailable → invalid_grant with the upstream text echoed; invalid_grant → invalid_grant with the upstream text echoed; a local RuntimeError → invalid_grant with the internal text echoed.

    One conformance constraint for whoever implements: the MCP SDK's TokenErrorCode literal only has the six 400 codes (invalid_request, invalid_client, invalid_grant, unauthorized_client, unsupported_grant_type, invalid_scope) — there is no temporarily_unavailable/server_error member, and TokenHandler.handle maps only TokenError to a 400 response. So anything that is not a definitive upstream rejection can only surface as a generic 500. In practice "distinguishable" therefore means: 400 invalid_grant exclusively for definitive rejections (the only case where the client should discard credentials), 500 with no details for everything else.

  4. zzstoatzz commented on Nov 2, 2026

    @zzstoatzz
    Collaborator

    This is fixed by #5011, released in v4.1.5: only an upstream invalid_grant maps to invalid_grant (with a sanitized description), and other upstream or local failures are no longer echoed back as invalid_grant.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    authbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions