Back to Fastmcp

authorize

docs/python-sdk/fastmcp-server-auth-handlers-authorize.mdx

3.2.42.8 KB
Original Source

fastmcp.server.auth.handlers.authorize

Enhanced authorization handler with improved error responses.

This module provides an enhanced authorization handler that wraps the MCP SDK's AuthorizationHandler to provide better error messages when clients attempt to authorize with unregistered client IDs.

The enhancement adds:

  • Content negotiation: HTML for browsers, JSON for API clients
  • Enhanced JSON responses with registration endpoint hints
  • Styled HTML error pages with registration links/forms
  • Link headers pointing to registration endpoints

Functions

create_unregistered_client_html <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/handlers/authorize.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

python
create_unregistered_client_html(client_id: str, registration_endpoint: str, discovery_endpoint: str, server_name: str | None = None, server_icon_url: str | None = None, title: str = 'Client Not Registered') -> str

Create styled HTML error page for unregistered client attempts.

Args:

  • client_id: The unregistered client ID that was provided
  • registration_endpoint: URL of the registration endpoint
  • discovery_endpoint: URL of the OAuth metadata discovery endpoint
  • server_name: Optional server name for branding
  • server_icon_url: Optional server icon URL
  • title: Page title

Returns:

  • HTML string for the error page

Classes

AuthorizationHandler <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/handlers/authorize.py#L161" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Authorization handler with enhanced error responses for unregistered clients.

This handler extends the MCP SDK's AuthorizationHandler to provide better UX when clients attempt to authorize without being registered. It implements content negotiation to return:

  • HTML error pages for browser requests
  • Enhanced JSON with registration hints for API clients
  • Link headers pointing to registration endpoints

This maintains OAuth 2.1 compliance (returns 400 for invalid client_id) while providing actionable guidance to fix the error.

Methods:

handle <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/handlers/authorize.py#L196" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

python
handle(self, request: Request) -> Response

Handle authorization request with enhanced error responses.

This method extends the SDK's authorization handler and intercepts errors for unregistered clients to provide better error responses based on the client's Accept header.

Args:

  • request: The authorization request

Returns:

  • Response (redirect on success, error response on failure)