# MCP email OAuth: the sign-in flow, step by step

> OAuth for an MCP email server: discovery, client registration, PKCE, consent, token refresh and revocation, with a tested Python client and the errors.

Source: https://trotta.email/learn/mcp-email-oauth

An MCP email server uses OAuth so an app can reach a mailbox without being handed a password or a key. The server answers 401 with a metadata address. The client finds the authorization server, registers, sends your human to approve with PKCE and trades the code for a short-lived token.

Updated December 3, 2026

## What happens when an app connects?

1. The client calls `/mcp` with no token and gets `401` with a `resource_metadata` address.
2. It reads that document (RFC 9728) to find the authorization server.
3. It reads the authorization server's metadata (RFC 8414) and checks the issuer and PKCE support.
4. It obtains a client ID.
5. It opens a browser. Your human signs in, picks inboxes and approves.
6. It trades the one-time code and the PKCE verifier for tokens.
7. It sends the access token in the `Authorization` header of every request.

If you are still choosing between sign-in and a key, start with [MCP email servers](https://trotta.email/learn/mcp-email-server). This page follows the sign-in on the wire, against `https://api.trotta.email/mcp`.

## What does the server say about itself?

GET /.well-known/oauth-authorization-server, shortened:

```json
{
  "issuer": "https://api.trotta.email",
  "authorization_endpoint": "https://api.trotta.email/oauth/authorize",
  "token_endpoint": "https://api.trotta.email/oauth/token",
  "registration_endpoint": "https://api.trotta.email/oauth/register",
  "revocation_endpoint": "https://api.trotta.email/oauth/revoke",
  "code_challenge_methods_supported": ["S256"],
  "client_id_metadata_document_supported": true,
  "authorization_response_iss_parameter_supported": true,
  "scopes_supported": ["mail:read", "mail:send"]
}
```

Two checks matter here. The `issuer` must be exactly the one you looked up. And `code_challenge_methods_supported` must list `S256`: the MCP specification says a client has to refuse a server that does not advertise PKCE.

## How does a client get a client ID?

| Method | When | Note |
| --- | --- | --- |
| Pre-registration | You already hold a client ID for this server | Use it before anything else |
| Client ID Metadata Document | No prior relationship, the common case | The client ID is an https address of your JSON file |
| Dynamic registration | Older servers and quick tests | Deprecated in the 2026-07-28 specification, kept for compatibility |

The script below registers dynamically because it runs on one machine with nothing hosted. Publish a metadata document for a real app.

## How do you run the whole OAuth flow in Python?

Install `requests` and run it. Your browser opens for the approval, and the script listens on `127.0.0.1:8765` for the answer. You need a Trotta Mail account to approve with.

`mcp_oauth.py`:

```python
import base64
import hashlib
import secrets
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qsl, urlencode, urlsplit

import requests

MCP = "https://api.trotta.email/mcp"
REDIRECT = "http://127.0.0.1:8765/callback"

# 1. Call with no token. The 401 says where the metadata is.
denied = requests.post(MCP, timeout=30)
challenge_header = denied.headers["www-authenticate"]
metadata_url = challenge_header.split('resource_metadata="')[1].split('"')[0]

# 2. Find the authorization server, and check what it says about itself.
resource = requests.get(metadata_url, timeout=30).json()
issuer = resource["authorization_servers"][0]
server = requests.get(f"{issuer}/.well-known/oauth-authorization-server", timeout=30).json()
assert server["issuer"] == issuer
assert "S256" in server["code_challenge_methods_supported"]

# 3. Register this client.
client_id = requests.post(server["registration_endpoint"], timeout=30, json={
    "client_name": "OAuth walkthrough",
    "redirect_uris": [REDIRECT],
    "token_endpoint_auth_method": "none",
}).json()["client_id"]

# 4. PKCE and state, then send your human to approve.
verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(verifier.encode()).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
state = secrets.token_urlsafe(24)
url = server["authorization_endpoint"] + "?" + urlencode({
    "response_type": "code", "client_id": client_id, "redirect_uri": REDIRECT,
    "scope": "mail:read mail:send", "state": state, "resource": resource["resource"],
    "code_challenge": challenge, "code_challenge_method": "S256",
})
answer = {}

class Callback(BaseHTTPRequestHandler):
    def do_GET(self):
        answer.update(parse_qsl(urlsplit(self.path).query))
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"Done. You can close this tab.")

    def log_message(self, *args):
        pass  # keep the code out of logs

listener = HTTPServer(("127.0.0.1", 8765), Callback)
print("Approve here:", url, flush=True)
webbrowser.open(url)
while "state" not in answer:
    listener.handle_request()

# 5. Check the answer before using it.
assert answer["state"] == state, "not the request we started"
assert answer.get("iss") == issuer, "answer from another server"
assert "code" in answer, answer.get("error")

# 6. Trade the code for tokens.
tokens = requests.post(server["token_endpoint"], timeout=30, data={
    "grant_type": "authorization_code", "code": answer["code"], "redirect_uri": REDIRECT,
    "client_id": client_id, "code_verifier": verifier, "resource": resource["resource"],
}).json()
print("scope:", tokens["scope"], "expires_in:", tokens["expires_in"])

# 7. Use the access token on every MCP request, in the header only.
listing = requests.post(MCP, timeout=30, headers={
    "Authorization": f"Bearer {tokens['access_token']}",
    "Accept": "application/json, text/event-stream",
    "MCP-Protocol-Version": "2026-07-28",
    "Mcp-Method": "tools/list",
}, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": {
    "io.modelcontextprotocol/protocolVersion": "2026-07-28",
    "io.modelcontextprotocol/clientCapabilities": {},
}}})
print([tool["name"] for tool in listing.json()["result"]["tools"]])

# 8. Refresh. The refresh token changes every time, so store the new one.
fresh = requests.post(server["token_endpoint"], timeout=30, data={
    "grant_type": "refresh_token", "refresh_token": tokens["refresh_token"], "client_id": client_id,
}).json()
print("new refresh token:", fresh["refresh_token"] != tokens["refresh_token"])

# 9. Revoke when you are done. This ends the whole grant.
requests.post(server["revocation_endpoint"], timeout=30,
              data={"token": fresh["refresh_token"], "client_id": client_id})
after = requests.post(MCP, timeout=30, headers={"Authorization": f"Bearer {fresh['access_token']}"})
print("after revoke:", after.status_code)
```

Output, tool list shortened:

```text
scope: mail:read mail:send expires_in: 3600
['list_inboxes', 'create_inbox', 'list_messages', 'read_message', ...]
new refresh token: True
after revoke: 401
```

A real client stores the refresh token as carefully as a password, and keeps codes and tokens out of its logs.

## How long do codes and tokens last?

| Item | Rules on Trotta Mail |
| --- | --- |
| Authorization code | 5 minutes, single use. A second use revokes the grant |
| Access token | 1 hour. Works at `/mcp` and nowhere else |
| Refresh token | 30 days from last use, replaced on every refresh |
| A spent refresh token sent again | `400 invalid_grant`, and the whole grant is revoked |

The last rule bites when two copies of a client share one token file. We replayed an old refresh token: the newer access token stopped working too.

## What can a connected app never get?

- Scopes beyond `mail:read` and `mail:send`. Asking for `mail:full`, `guard:release` or `admin` is `invalid_scope`.
- Held mail. It stays held until a human releases it.
- Login codes and reset links in a human's mailbox. They are sealed.
- More than your human picked: chosen inboxes, or one pod.
- New inboxes. `create_inbox` answers `not_for_connected_apps`.

Your human also sets a send mode on the consent screen: ask before every email (the default), drafts only, or send without asking.

## What do the OAuth errors mean?

| Answer | Cause | Fix |
| --- | --- | --- |
| `401` with `invalid_token` | Expired, revoked or wrong token | Refresh, or sign in again |
| `403` with `insufficient_scope` | The grant lacks a scope the tool needs | Ask again for it, plus the scopes you had |
| `invalid_target` | `resource` is missing or wrong | Send the MCP server's address as `resource` |
| `invalid_redirect_uri` | Neither https nor loopback | Use https, or http on `127.0.0.1` or `localhost` |
| `invalid_scope` | Asked for more than a connection may have | Ask for `mail:read mail:send` |
| `invalid_grant` | Code or refresh token spent or expired | Start the flow again |

You do not need any of this code to connect ChatGPT, Claude, Claude Code, Codex or Cursor. They run the flow from the server address: see [connect an assistant](https://trotta.email/docs/connect). Sign-in limits what an app may do, not what an email may ask it to do, so read [the lethal trifecta](https://trotta.email/learn/lethal-trifecta-email) before you grant send access.

## Questions

### Do I need OAuth if I already have an API key?

No. A key in the `Authorization` header suits an agent that runs unattended. OAuth is for connecting an app on behalf of a human.

### What is the resource parameter for?

It binds the token to one MCP server (RFC 8707). The MCP specification requires clients to send it in both the authorization and the token request.

### Why check iss in the callback?

It shows which authorization server answered, which blocks mix-up attacks. The 2026-07-28 specification requires clients to compare it when the server sends it.

### Can a connected app release held mail?

No. A grant is never given `guard:release`. Releasing needs a signed-in human, or a key a human gave that scope.

## Sources

- [Model Context Protocol specification 2026-07-28: authorization](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization)
- [Model Context Protocol specification 2026-07-28: client registration](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/client-registration)
- [Model Context Protocol specification 2026-07-28: authorization security considerations](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization/security-considerations)
- [RFC 9728, OAuth 2.0 Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728.html)
- [RFC 8414, OAuth 2.0 Authorization Server Metadata](https://www.rfc-editor.org/rfc/rfc8414.html)
- [RFC 8707, Resource Indicators for OAuth 2.0](https://www.rfc-editor.org/rfc/rfc8707.html)

## Related

- [MCP email servers: tools, authorization and safety](https://trotta.email/learn/mcp-email-server) Guides
- [MCP](https://trotta.email/docs/mcp) Docs
- [Connect ChatGPT and Claude](https://trotta.email/docs/connect) Docs
- [MCP](https://trotta.email/integrations/mcp) Integrations
- [Email MCP servers](https://trotta.email/compare/email-mcp-servers) Compare
- [The lethal trifecta for an AI agent with email](https://trotta.email/learn/lethal-trifecta-email) Guides

Give your agent an inbox of its own. Free for three agent inboxes and you. No card.

[Get an inbox](https://trotta.email/signup) [Read the docs](https://trotta.email/docs)
