# `AshAi.Mcp.OAuth`
[🔗](https://github.com/ash-project/ash_ai/blob/v1.5.6/lib/ash_ai/mcp/oauth.ex#L6)

An OAuth 2.1 client for MCP servers, following the MCP authorization spec
(revision 2026-07-28).

AshAi never stores credentials. Everything it needs to keep (registered
clients, tokens, and authorizations in progress) goes through a
`AshAi.Mcp.OAuth.Store` you implement, so you decide where it lives and how
it is encrypted. `mix ash_ai.gen.mcp_oauth` generates one backed by
`ash_postgres` and `ash_cloak`, with routes for the flow below. See the
[MCP Client Authorization](mcp-client-authorization.md) guide.

## Flow

1. Connect to an MCP server with `auth: {AshAi.Mcp.OAuth, opts}`, where
   `opts` includes `:owner`. The client asks `headers/2` for a token before
   each request.
2. With no usable token, the request fails with
   `{:error, {:authorization_required, info}}`. Send the user to the URL from
   `authorize_url/3`, passing `challenge: info.www_authenticate` when it is
   set.
3. On the redirect back, call `handle_callback/3` with the query params and
   the signed-in owner. It stores the token, and later requests use it.
4. Tokens are refreshed before they expire, under the store's lock. When a
   refresh token stops working, requests fail with `:authorization_required`
   again.
5. A server that needs more scopes answers 403, and the request fails with
   `{:error, {:insufficient_scope, info}}`. Send the user through
   `authorize_url/3` with `challenge: info.www_authenticate`; the new
   request includes the scopes already granted.
6. `disconnect/3` revokes the tokens and deletes them, when the user
   disconnects or before their account is deleted.

## Requests to server-supplied URLs

Discovery fetches URLs that the MCP server supplies, directly or through the
metadata it points to. AshAi requires HTTPS for them and only connects to
public addresses, checking every address a host resolves to as it connects,
so a server can't aim requests at cloud metadata endpoints or other
services on your network. List the exceptions, such as `"localhost"` in
development, in `:allowed_private_hosts`.

Responses are limited to 256 KiB and requests to 10 seconds. Redirects
aren't followed.

A proxy, a named `finch:` pool, or a custom `adapter:` in `req_options`
takes requests out of the address check's reach, so they need
`allowed_private_hosts: :all`, for example with an egress proxy that
enforces it. Without it they raise rather than go unchecked.

## Options

* `:store` - Required. The `AshAi.Mcp.OAuth.Store` as `module` or `{module, store_opts}`.

* `:owner` (`t:term/0`) - Whose tokens to use, such as a user id. Required by the `AshAi.Mcp.Client.Auth` callbacks.

* `:redirect_uri` (`t:String.t/0`) - Where the authorization server redirects back to. Must be HTTPS or a loopback URL. Required by `authorize_url/3`.

* `:redirect_uris` (list of `t:String.t/0`) - Every redirect URI to register or list in the Client ID Metadata Document. Defaults to `[redirect_uri]`.

* `:client_name` (`t:String.t/0`) - Shown to users on consent screens. The default value is `"AshAi MCP Client"`.

* `:client_uri` (`t:String.t/0`) - Your application's home page.

* `:logo_uri` (`t:String.t/0`) - Your application's logo.

* `:client_metadata_url` (`t:String.t/0`) - The HTTPS URL where you serve `client_metadata_document/1` (see `AshAi.Mcp.OAuth.ClientMetadataPlug`). Enables Client ID Metadata Documents.

* `:pre_registered` - Client credentials you registered yourself, as `%{server_url => [issuer: ..., client_id: ..., client_secret: ...]}` or a function from an MCP server's URL to those credentials or `nil`. They're used only for that server, and only while it names `issuer` as its authorization server, so another server can't borrow them by naming the same authorization server.

* `:token_endpoint_auth_method` - The token endpoint authentication to request through Dynamic Client Registration. Valid values are "none", "client_secret_basic", "client_secret_post" The default value is `"none"`.

* `:application_type` - The application type to register. Defaults to `native` for loopback redirect URIs and `web` otherwise. Valid values are "web", "native"

* `:challenge` (`t:term/0`) - A `WWW-Authenticate` header value (or a parsed challenge) from the server. `authorize_url/3` uses its `resource_metadata` and `scope`.

* `:scope` - Extra scopes for `authorize_url/3` to request.

* `:offline_access` (`t:boolean/0`) - Whether to request `offline_access` (for a refresh token) when the authorization server lists it. The default value is `true`.

* `:refresh_skew` (`t:non_neg_integer/0`) - Refresh tokens that expire within this many seconds. The default value is `60`.

* `:pending_ttl` (`t:pos_integer/0`) - Seconds a pending authorization stays valid. The default value is `600`.

* `:allowed_private_hosts` - Hosts that may resolve to loopback, private, or other non-public addresses, such as `["localhost"]` in development or an internal authorization server's hostname. Loopback hosts listed here may also use plain HTTP. `:all` turns the check off, which a proxy, named `finch:` pool, or custom `adapter:` in `req_options` requires. The default value is `[]`.

* `:req_options` (`t:keyword/0`) - Options merged into every `Req.new/1`, such as `plug:` in tests or `connect_options: [proxy: ...]` for an egress proxy. The default value is `[]`.

# `opts`

```elixir
@type opts() :: keyword()
```

# `access_token`

```elixir
@spec access_token(String.t(), term(), opts()) ::
  {:ok, AshAi.Mcp.OAuth.Token.t()} | {:error, term()}
```

Returns a usable token for `owner` at the MCP server `server_url`,
refreshing it first if it expires within `:refresh_skew` seconds.

# `authorize_url`

```elixir
@spec authorize_url(String.t(), term(), opts()) ::
  {:ok, String.t(), AshAi.Mcp.OAuth.Pending.t()} | {:error, term()}
```

Returns the authorization URL to send `owner` to for the MCP server at
`server_url`, and the `AshAi.Mcp.OAuth.Pending` it stored.

Discovers the authorization server, obtains a client ID, and selects scopes:
those from `:challenge` and `:scope`, or else the server's
`scopes_supported`, plus any scopes `owner` was already granted.

# `canonical_resource`

See `AshAi.Mcp.OAuth.Discovery.canonical_resource/1`.

# `client_metadata_document`

See `AshAi.Mcp.OAuth.Registration.client_metadata_document/1`.

# `disconnect`

```elixir
@spec disconnect(String.t(), term(), opts()) ::
  {:ok, :revoked | :unsupported | :not_connected} | {:error, term()}
```

Disconnects `owner` from the MCP server at `server_url`: revokes their
tokens at the authorization server (RFC 7009) when it supports
revocation, and deletes them from the store.

The tokens are deleted even when revoking them fails, so the owner is
disconnected from your application either way.
`{:error, {:revocation_failed, reason}}` means the authorization server may
still consider the grant active, until it expires or the user revokes it
there.

Returns `{:ok, :revoked}`, `{:ok, :unsupported}` when the authorization
server doesn't offer revocation, or `{:ok, :not_connected}` when `owner`
had no tokens.

# `discover`

See `AshAi.Mcp.OAuth.Discovery.discover/2`.

# `handle_callback`

```elixir
@spec handle_callback(map(), term(), opts()) ::
  {:ok, AshAi.Mcp.OAuth.Token.t(), AshAi.Mcp.OAuth.Pending.t()}
  | {:error, term()}
```

Completes an authorization from the query params of the redirect back.

`owner` is whoever completes the redirect, such as the signed-in user, and
must be the owner the authorization was started for. Otherwise a user
could start an authorization, get someone else to open its URL, and
receive that person's tokens.

Consumes the pending authorization for `state`, validates the response's
`iss` (RFC 9207), exchanges the code, and stores the token.

# `parse_www_authenticate`

See `AshAi.Mcp.OAuth.Discovery.parse_www_authenticate/1`.

# `refresh`

```elixir
@spec refresh(String.t(), term(), opts()) ::
  {:ok, AshAi.Mcp.OAuth.Token.t()} | {:error, term()}
```

Refreshes `owner`'s token for `server_url` now, even if it hasn't expired.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
