PrefectHQ/fastmcp · error · RuntimeError

No access token available. Cannot extract claim '{self.claim

Error message

No access token available. Cannot extract claim '{self.claim_name}'.

What it means

The Claim dependency extracts a named claim from the current request's access token. Before reading claims it checks get_access_token(); when no token is present it raises this RuntimeError naming the claim it was asked for. It's thrown rather than returning None so callers get an explicit signal that authentication is absent, distinct from the claim simply being missing.

Source

Thrown at fastmcp_slim/fastmcp/server/dependencies.py:1341

            return token.claims.get("sub", "unknown")
        ```
    """
    return cast(AccessToken, _CurrentAccessToken())


# --- Token Claim dependency ---


class _TokenClaim(Dependency[str]):
    """Dependency that extracts a specific claim from the access token."""

    def __init__(self, claim_name: str):
        self.claim_name = claim_name

    async def __aenter__(self) -> str:
        token = get_access_token()
        if token is None:
            raise RuntimeError(
                f"No access token available. Cannot extract claim '{self.claim_name}'."
            )
        value = token.claims.get(self.claim_name)
        if value is None:
            raise RuntimeError(
                f"Claim '{self.claim_name}' not found in access token. "
                f"Available claims: {list(token.claims.keys())}"
            )
        return str(value)

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_value: BaseException | None,
        traceback: TracebackType | None,
    ) -> None:
        pass

View on GitHub (pinned to 1f02114297)

Solutions

  1. Configure authentication on the server and ensure the client sends a valid Bearer token
  2. Make the claim optional: call get_access_token() directly and handle None
  3. Check whether the specific endpoint/transport is exempt from auth when it shouldn't be (or vice versa)
  4. In tests, inject a mock AccessToken containing the claim

Example fix

// before
async def whoami(user_id: Claim) -> str:  # RuntimeError when unauthenticated
    return user_id
// after
from fastmcp.server.dependencies import get_access_token
async def whoami() -> str:
    token = get_access_token()
    return str(token.claims.get("sub")) if token else "anonymous"
Defensive patterns

Strategy: try-catch

Validate before calling

from fastmcp.server.dependencies import get_access_token
token = get_access_token()
if token is None or claim_name not in token.claims:
    ...  # handle missing token/claim before using Claim

Type guard

from fastmcp.server.dependencies import get_access_token

def has_claim(claim_name: str) -> bool:
    token = get_access_token()
    return token is not None and claim_name in token.claims

Try / catch

try:
    async with Claim('sub') as sub:
        return sub
except RuntimeError:
    return 'anonymous'

Prevention

When it happens

Trigger: Entering `with Claim("sub") as sub:` on a request without authentication — no auth provider configured, missing/invalid Authorization header, or called outside a request context entirely.

Common situations: Local development over stdio (no auth); routes exposed without the auth middleware; unit tests without token fixtures; a client that failed token acquisition silently.

Related errors


AI-assisted analysis of PrefectHQ/fastmcp@1f02114297 (2026-08-29). Data as JSON: /api/errors/150caf05df9f6d1e. Report an issue: GitHub.