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 guide.
Flow
- Connect to an MCP server with
auth: {AshAi.Mcp.OAuth, opts}, whereoptsincludes:owner. The client asksheaders/2for a token before each request. - With no usable token, the request fails with
{:error, {:authorization_required, info}}. Send the user to the URL fromauthorize_url/3, passingchallenge: info.www_authenticatewhen it is set. - On the redirect back, call
handle_callback/3with the query params and the signed-in owner. It stores the token, and later requests use it. - Tokens are refreshed before they expire, under the store's lock. When a
refresh token stops working, requests fail with
:authorization_requiredagain. - A server that needs more scopes answers 403, and the request fails with
{:error, {:insufficient_scope, info}}. Send the user throughauthorize_url/3withchallenge: info.www_authenticate; the new request includes the scopes already granted. disconnect/3revokes 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. TheAshAi.Mcp.OAuth.Storeasmoduleor{module, store_opts}.:owner(term/0) - Whose tokens to use, such as a user id. Required by theAshAi.Mcp.Client.Authcallbacks.:redirect_uri(String.t/0) - Where the authorization server redirects back to. Must be HTTPS or a loopback URL. Required byauthorize_url/3.:redirect_uris(list ofString.t/0) - Every redirect URI to register or list in the Client ID Metadata Document. Defaults to[redirect_uri].:client_name(String.t/0) - Shown to users on consent screens. The default value is"AshAi MCP Client".:client_uri(String.t/0) - Your application's home page.:logo_uri(String.t/0) - Your application's logo.:client_metadata_url(String.t/0) - The HTTPS URL where you serveclient_metadata_document/1(seeAshAi.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 ornil. They're used only for that server, and only while it namesissueras 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 tonativefor loopback redirect URIs andwebotherwise. Valid values are "web", "native":challenge(term/0) - AWWW-Authenticateheader value (or a parsed challenge) from the server.authorize_url/3uses itsresource_metadataandscope.:scope- Extra scopes forauthorize_url/3to request.:offline_access(boolean/0) - Whether to requestoffline_access(for a refresh token) when the authorization server lists it. The default value istrue.:refresh_skew(non_neg_integer/0) - Refresh tokens that expire within this many seconds. The default value is60.:pending_ttl(pos_integer/0) - Seconds a pending authorization stays valid. The default value is600.: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.:allturns the check off, which a proxy, namedfinch:pool, or customadapter:inreq_optionsrequires. The default value is[].:req_options(keyword/0) - Options merged into everyReq.new/1, such asplug:in tests orconnect_options: [proxy: ...]for an egress proxy. The default value is[].
Summary
Functions
Returns a usable token for owner at the MCP server server_url,
refreshing it first if it expires within :refresh_skew seconds.
Returns the authorization URL to send owner to for the MCP server at
server_url, and the AshAi.Mcp.OAuth.Pending it stored.
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.
Completes an authorization from the query params of the redirect back.
Refreshes owner's token for server_url now, even if it hasn't expired.
Types
@type opts() :: keyword()
Functions
@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.
@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.
See AshAi.Mcp.OAuth.Registration.client_metadata_document/1.
@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.
@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.
@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.