Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164---title: authorizationsidebarTitle: authorization---
# `fastmcp.utilities.authorization`
Authorization checks for FastMCP components.
Auth checks are callables that receive an ``AuthContext`` and return True toallow access or False to deny it. They can also raise ``AuthorizationError`` todeny with a custom message; other exceptions are masked and treated as denial.
## Functions
### `require_scopes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L143" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrequire_scopes(*scopes: str) -> AuthCheck```
Require all of the given OAuth scopes.
### `require_roles` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L148" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrequire_roles(*roles: str) -> AuthCheck```
Require all of the given roles, read from the token's claims.
Roles and groups are not part of OIDC, so every identity provider puts themsomewhere different: `realm_access.roles` on Keycloak, `roles` on MicrosoftEntra, `cognito:groups` on AWS Cognito, `permissions` or a namespaced customclaim on Auth0. `extract` receives the token's claims and returns thecaller's roles, which keeps that provider-specific knowledge at the callsite instead of guessing it here.
```pythonfrom fastmcp.server.auth import require_roles
keycloak = require_roles("admin", extract=lambda c: c["realm_access"]["roles"])cognito = require_roles("admins", extract=lambda c: c["cognito:groups"])```
A token missing the claim entirely is denied rather than treated as anerror, so `extract` may index into the claims without guarding. Anextractor returning a bare string is treated as one role, since a providerthat stores a single role as a scalar is common.
Unlike `require_scopes`, this check cannot signal a shortfall: OAuth has noway to request a role, so there is no `insufficient_scope` challenge toemit. A role denial is therefore reported as a plain `AuthorizationError`,and it suppresses any scope shortfall alongside it — a caller blocked bytheir role must not be told to go obtain a scope that would not help.Scope shortfalls are still reported normally whenever the role checkpasses.
**Args:**- `*roles`: Roles the caller must hold. All are required (AND logic).- `extract`: Callable mapping the token's claims to the caller's roles.
**Raises:**- `ValueError`: If no roles are given, which would allow any authenticatedcaller and is more likely a mistake than an intent.
### `restrict_tag` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L197" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrestrict_tag(tag: str) -> AuthCheck```
Require scopes when the accessed component has a specific tag.
### `scope_requirements` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L202" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonscope_requirements(checks: AuthCheck | list[AuthCheck], ctx: AuthContext) -> list[str] | None```
Scopes a check list requires but the token lacks, without running it.
Returns ``None`` when the list contains any opaque (non-scope) check. Such acheck might deny for a reason unrelated to scopes, and evaluating it herewould run authorization logic — with whatever side effects it carries —outside its normal place in the chain. Since its verdict is unknown, itssiblings' scopes must not be disclosed either, so the whole list is withheld.
When every check is scope-aware, the result is their combined shortfall,computed purely from the token and component (an empty list means the list isalready satisfied). This lets a shortfall be aggregated across authorizationlayers without evaluating anything that would otherwise be skipped.
### `run_auth_checks_with_shortfall` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L253" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrun_auth_checks_with_shortfall(checks: AuthCheck | list[AuthCheck], ctx: AuthContext) -> tuple[bool, list[str]]```
Run auth checks with AND logic, classifying the denial cause.
Returns ``(authorized, missing_scopes)``. ``missing_scopes`` names everyscope the caller must obtain to satisfy *all* scope requirements at once:the union of the shortfalls across every scope-aware check, not just thefirst one to fail. Reporting only the first would strand a caller in astep-up loop — it obtains that scope, retries, and is denied again for thenext — so the union is what makes a single re-authorization converge.
The challenge is withheld entirely (an empty list, which the caller surfacesas a plain ``AuthorizationError``) unless every non-scope check passes. Acustom policy denial — a tenant check, say — must never be reported as an``insufficient_scope`` shortfall, and must never name the scopes of acomponent the caller could not otherwise reach. To guarantee that, theopaque checks are all evaluated before any scope is disclosed; a shortfallis only reported once they have all passed.
An ``AuthorizationError`` raised by a check propagates unchanged.
### `run_auth_checks` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L304" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrun_auth_checks(checks: AuthCheck | list[AuthCheck], ctx: AuthContext) -> bool```
Run auth checks with AND logic, stopping at the first failure.
## Classes
### `AuthContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L27" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Context passed to auth check callables.
**Attributes:**- `token`: The current access token, or None if unauthenticated.- `component`: The tool, resource, resource template, or prompt being accessed.- `tool`: Backwards-compatible alias for component when it is a Tool.
**Methods:**
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L40" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontool(self) -> Tool | None```
Backwards-compatible access to the component as a Tool.