---
title: "Oauth"
description: "OAuth authentication support for MCP clients API Documentation"
icon: "code"
github: "https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp_use/client/auth/oauth.py"
---

import {RandomGradientBackground} from "/snippets/gradient.jsx"

<Callout type="info" title="Source Code">
View the source code for this module on GitHub: <a href='https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp_use/client/auth/oauth.py' target='_blank' rel='noopener noreferrer'>https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp_use/client/auth/oauth.py</a>
</Callout>

OAuth authentication support for MCP clients.

## ClientRegistrationResponse

<div>
<RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
<div className="text-black">
<div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> ClientRegistrationResponse</div>

Dynamic Client Registration response.

    It represents the response from an OAuth server
    when you dinamically register a new OAuth client.

</div>
</RandomGradientBackground>
```python
from mcp_use.client.auth.oauth import ClientRegistrationResponse
```

<Card type="info">
**Attributes**
>
<ParamField body="client_id" type="str" required="True" >   MCP client instance </ParamField>
<ParamField body="client_secret" type="str | None" required="True" >   MCP client instance </ParamField>
<ParamField body="client_id_issued_at" type="int | None" required="True" >   MCP client instance </ParamField>
<ParamField body="client_secret_expires_at" type="int | None" required="True" >   MCP client instance </ParamField>
<ParamField body="redirect_uris" type="list[str] | None" required="True" >   List of items </ParamField>
<ParamField body="grant_types" type="list[str] | None" required="True" >   List of items </ParamField>
<ParamField body="response_types" type="list[str] | None" required="True" >   List of items </ParamField>
<ParamField body="client_name" type="str | None" required="True" >   MCP client instance </ParamField>
<ParamField body="token_endpoint_auth_method" type="str | None" required="True" >   String value </ParamField>

</Card>

<Card type="info">
### `method` __init__

Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.

**Parameters**
><ParamField body="data" type="Any" required="True" >   Parameter value </ParamField>

**Signature**
```python wrap
def __init__(data: Any):
```

</Card>
</div>

## FileTokenStorage

<div>
<RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
<div className="text-black">
<div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> FileTokenStorage</div>

File-based token storage.

    It's responsible for:

    - Saving OAuth tokens to disk after auth
    - Loading saved tokens when the app restarts
    - Deleting tokens when they're revoked
    - Organizing tokens by server URL

</div>
</RandomGradientBackground>
```python
from mcp_use.client.auth.oauth import FileTokenStorage
```

<Card type="info">
### `method` __init__

Initialize token storage.


**Parameters**
><ParamField body="base_dir" type="pathlib.Path | None" default="None" >   Base directory for token storage. Defaults to ~/.mcp_use/tokens </ParamField>

**Signature**
```python wrap
def __init__(base_dir: pathlib.Path | None = None):
```

</Card>
<Card type="info">
### `method` delete_tokens

Delete tokens for a server.


**Parameters**
><ParamField body="server_url" type="str" required="True" >   Server name or configuration </ParamField>

**Signature**
```python wrap
def delete_tokens(server_url: str):
```

</Card>

<Card type="info">
### `method` load_tokens

Load tokens from file.


**Parameters**
><ParamField body="server_url" type="str" required="True" >   Server name or configuration </ParamField>

**Returns**
><ResponseField name="returns" type="mcp_use.client.auth.oauth.TokenData | None" />

**Signature**
```python wrap
def load_tokens(server_url: str):
```

</Card>

<Card type="info">
### `method` save_tokens

Save tokens to file.


**Parameters**
><ParamField body="server_url" type="str" required="True" >   Server name or configuration </ParamField>
><ParamField body="tokens" type="dict[str, Any]" required="True" >   Dictionary of key-value pairs </ParamField>

**Signature**
```python wrap
def save_tokens(server_url: str, tokens: dict[str, Any]):
```

</Card>

</div>

## OAuth

<div>
<RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
<div className="text-black">
<div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> OAuth</div>

OAuth authentication handler for MCP clients.

    This is the main class that handles all the authentication
    It has several features:

    - Discovers OAuth server capabilities automatically
    - Registers client dynamically when possible
    - Manages token storage and refresh automaticlly

</div>
</RandomGradientBackground>
```python
from mcp_use.client.auth.oauth import OAuth
```

<Card type="info">
### `method` __init__

Initialize OAuth handler.


**Parameters**
><ParamField body="server_url" type="str" required="True" >   The MCP server URL </ParamField>
><ParamField body="token_storage" type="mcp_use.client.auth.oauth.FileTokenStorage | None" default="None" >   Token storage implementation. Defaults to FileTokenStorage </ParamField>
><ParamField body="scope" type="str | None" default="None" >   OAuth scopes to request </ParamField>
><ParamField body="client_id" type="str | None" default="None" >   OAuth client ID. If not provided, will attempt dynamic registration </ParamField>
><ParamField body="client_secret" type="str | None" default="None" >   OAuth client secret (for confidential clients) </ParamField>
><ParamField body="callback_port" type="int | None" default="None" >   Port for local callback server, if empty, 8080 is used </ParamField>
><ParamField body="oauth_provider" type="mcp_use.client.auth.oauth.OAuthClientProvider | None" default="None" >   OAuth client provider to prevent metadata discovery </ParamField>
><ParamField body="client_metadata_url" type="str | None" default="None" >   Field used to authenticate with CIMD </ParamField>

**Signature**
```python wrap
def __init__(server_url: str, token_storage: mcp_use.client.auth.oauth.FileTokenStorage | None = None, scope: str | None = None, client_id: str | None = None, client_secret: str | None = None, callback_port: int | None = None, oauth_provider: mcp_use.client.auth.oauth.OAuthClientProvider | None = None, client_metadata_url: str | None = None):
```

</Card>
<Card type="info">
### `method` authenticate

Perform OAuth authentication flow.


**Returns**
><ResponseField name="returns" type="mcp_use.client.auth.bearer.BearerAuth" />

**Signature**
```python wrap
def authenticate():
```

</Card>

<Card type="info">
### `method` initialize

Initialize OAuth and return bearer auth if tokens exist.


**Parameters**
><ParamField body="client" type="httpx.AsyncClient" required="True" >   MCP client instance </ParamField>

**Returns**
><ResponseField name="returns" type="mcp_use.client.auth.bearer.BearerAuth | None" />

**Signature**
```python wrap
def initialize(client: httpx.AsyncClient):
```

</Card>

<Card type="info">
### `method` refresh_token

Refresh the access token if possible.


**Returns**
><ResponseField name="returns" type="mcp_use.client.auth.bearer.BearerAuth | None" />

**Signature**
```python wrap
def refresh_token():
```

</Card>

</div>

## OAuthClientProvider

<div>
<RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
<div className="text-black">
<div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> OAuthClientProvider</div>

OAuth client provider configuration for a specific server.

    This contains all the information needed to authenticate with an OAuth server
    without needing to discover metadata or register clients dynamically.

</div>
</RandomGradientBackground>
```python
from mcp_use.client.auth.oauth import OAuthClientProvider
```

<Card type="info">
**Attributes**
>
<ParamField body="id" type="str" required="True" >   String value </ParamField>
<ParamField body="display_name" type="str" required="True" >   Name identifier </ParamField>
<ParamField body="metadata" type="mcp_use.client.auth.oauth.ServerOAuthMetadata | dict[str, typing.Any]" required="True" >   Dictionary of key-value pairs </ParamField>

</Card>

<Card type="info">
### `method` __init__

Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.

**Parameters**
><ParamField body="data" type="Any" required="True" >   Parameter value </ParamField>

**Signature**
```python wrap
def __init__(data: Any):
```

</Card>
<Card type="info">
### `property` oauth_metadata

Get OAuth metadata as ServerOAuthMetadata instance.


**Returns**
><ResponseField name="returns" type="mcp_use.client.auth.oauth.ServerOAuthMetadata" />

**Signature**
```python wrap
def oauth_metadata():
```

</Card>

</div>

## ProtectedResourceMetadata

<div>
<RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
<div className="text-black">
<div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> ProtectedResourceMetadata</div>

PRM (Protected Resource Metadata) can have metadata
    describing their configuration. It could contain information
    about the OAuth metadata.

</div>
</RandomGradientBackground>
```python
from mcp_use.client.auth.oauth import ProtectedResourceMetadata
```

<Card type="info">
**Attributes**
>
<ParamField body="resource" type="str" required="True" >   String value </ParamField>
<ParamField body="authorization_servers" type="list[str]" required="True" >   Server name or configuration </ParamField>
<ParamField body="scopes_supported" type="list[str] | None" required="True" >   List of items </ParamField>

</Card>

<Card type="info">
### `method` __init__

Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.

**Parameters**
><ParamField body="data" type="Any" required="True" >   Parameter value </ParamField>

**Signature**
```python wrap
def __init__(data: Any):
```

</Card>
</div>

## ServerOAuthMetadata

<div>
<RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
<div className="text-black">
<div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> ServerOAuthMetadata</div>

OAuth metadata from MCP server with flexible field support.
    It is essentially a configuration that tells MCP client:

    - Where to send users for authorization
    - Where to exchange the codes for tokens
    - Which OAuth features are supported
    - Where to register new users with DCR

</div>
</RandomGradientBackground>
```python
from mcp_use.client.auth.oauth import ServerOAuthMetadata
```

<Card type="info">
**Attributes**
>
<ParamField body="issuer" type="pydantic.networks.HttpUrl" required="True" >   Parameter value </ParamField>
<ParamField body="authorization_endpoint" type="pydantic.networks.HttpUrl" required="True" >   Parameter value </ParamField>
<ParamField body="token_endpoint" type="pydantic.networks.HttpUrl" required="True" >   Parameter value </ParamField>
<ParamField body="userinfo_endpoint" type="pydantic.networks.HttpUrl | None" required="True" >   Parameter value </ParamField>
<ParamField body="revocation_endpoint" type="pydantic.networks.HttpUrl | None" required="True" >   Parameter value </ParamField>
<ParamField body="introspection_endpoint" type="pydantic.networks.HttpUrl | None" required="True" >   Parameter value </ParamField>
<ParamField body="registration_endpoint" type="pydantic.networks.HttpUrl | None" required="True" >   Parameter value </ParamField>
<ParamField body="jwks_uri" type="pydantic.networks.HttpUrl | None" required="True" >   Parameter value </ParamField>
<ParamField body="response_types_supported" type="list[str]" required="True" >   List of items </ParamField>
<ParamField body="subject_types_supported" type="list[str]" required="True" >   List of items </ParamField>
<ParamField body="id_token_signing_alg_values_supported" type="list[str]" required="True" >   List of items </ParamField>
<ParamField body="scopes_supported" type="list[str] | None" required="True" >   List of items </ParamField>
<ParamField body="token_endpoint_auth_methods_supported" type="list[str]" required="True" >   List of items </ParamField>
<ParamField body="claims_supported" type="list[str] | None" required="True" >   List of items </ParamField>
<ParamField body="code_challenge_methods_supported" type="list[str] | None" required="True" >   List of items </ParamField>
<ParamField body="client_id_metadata_document_supported" type="bool | None" required="True" >   MCP client instance </ParamField>

</Card>

<Card type="info">
### `method` __init__

Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.

**Parameters**
><ParamField body="data" type="Any" required="True" >   Parameter value </ParamField>

**Signature**
```python wrap
def __init__(data: Any):
```

</Card>
</div>

## TokenData

<div>
<RandomGradientBackground className="rounded-lg p-4 w-full h-full rounded-full">
<div className="text-black">
<div className="text-black font-bold text-xl mb-2 mt-8"><code className="!text-black">class</code> TokenData</div>

OAuth token data.

    This is the information received after
    successfull authentication

</div>
</RandomGradientBackground>
```python
from mcp_use.client.auth.oauth import TokenData
```

<Card type="info">
**Attributes**
>
<ParamField body="access_token" type="str" required="True" >   String value </ParamField>
<ParamField body="token_type" type="str" required="True" >   String value </ParamField>
<ParamField body="expires_at" type="float | None" required="True" >   Parameter value </ParamField>
<ParamField body="refresh_token" type="str | None" required="True" >   String value </ParamField>
<ParamField body="scope" type="str | None" required="True" >   String value </ParamField>

</Card>

<Card type="info">
### `method` __init__

Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.

**Parameters**
><ParamField body="data" type="Any" required="True" >   Parameter value </ParamField>

**Signature**
```python wrap
def __init__(data: Any):
```

</Card>
</div>
