# Connect your own app (/guides/mcp-oauth)

This page is for developers who build an app, agent or MCP client that talks to the Alienmail MCP server. To connect an existing AI tool such as Claude, ChatGPT or Cursor, see [Alienmail MCP server](/guides/mcp-server).

```txt
https://app.alienmail.io/api/mcp
```

## Pick how your app signs in [#pick-how-your-app-signs-in]

| | API key | OAuth |
|---|---|---|
| Use it when | Your own system works with your own workspace, with no person present. | Other people connect their Alienmail workspace to your app. |
| Who the app acts as | The key, with the role you gave it. | The person who allowed it, with their role in the workspace they picked. |
| Setup | Create a key in **Workspace settings → Integrations**. | None. Your app registers itself and sends the person to Alienmail to allow it. |
| Sent as | `Authorization: Bearer YOUR_API_KEY` | `Authorization: Bearer <access token>` |

<Callout type="info" title="Using an MCP SDK?">
The official MCP SDKs and most MCP clients do the whole OAuth flow on this page for you: discovery, registration, PKCE and token refresh. Give them the server address and a redirect URI. Read on if you write the flow yourself or want to know what happens.
</Callout>

## Talk to the server [#talk-to-the-server]

The server speaks MCP over Streamable HTTP. Send each JSON-RPC message as a `POST` with a JSON body, and the answer comes back as JSON in the response. A notification (a message without an `id`) is answered `202` with no body.

```bash
curl https://app.alienmail.io/api/mcp \
  -H "Authorization: Bearer $ALIENMAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"my-app","version":"1.0.0"}}}'
```

Then list the tools and call one:

```bash
curl https://app.alienmail.io/api/mcp \
  -H "Authorization: Bearer $ALIENMAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'

curl https://app.alienmail.io/api/mcp \
  -H "Authorization: Bearer $ALIENMAIL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_campaigns","arguments":{"status":"ACTIVE"}}}'
```

- The server offers **tools** only. `resources/list` and `prompts/list` answer empty lists.
- `tools/list` returns only the tools this key or connection may call, each with its description and input schema. Read them from there; they are the source of truth.
- Each tool has a `title` and `annotations`: `readOnlyHint`, `destructiveHint`, `idempotentHint` and `openWorldHint`. Use them to decide which calls to confirm with the person. They are hints: the server still checks every call.
- A key or connection works in one workspace, so no tool asks for a workspace id.
- The older SSE transport also works: `GET` the same address with `Accept: text/event-stream`. At most 5 streams can be open at once for one key or connection.

That is all an API key needs. The rest of this page is the OAuth flow.

## OAuth step by step [#oauth-step-by-step]

Alienmail is its own OAuth 2.1 authorization server for the MCP server. The flow is the authorization code flow with PKCE.

### 1. Discover the endpoints [#1-discover-the-endpoints]

A request without credentials is answered `401` with a header that says where to look:

```http
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://app.alienmail.io/.well-known/oauth-protected-resource/api/mcp", scope="mcp:read mcp:write"
```

Two documents describe the rest. You can also read them directly:

| Document | Address |
|---|---|
| Protected resource metadata (RFC 9728) | `https://app.alienmail.io/.well-known/oauth-protected-resource/api/mcp` |
| Authorization server metadata (RFC 8414) | `https://app.alienmail.io/.well-known/oauth-authorization-server` |

The endpoints they name:

| Endpoint | Address |
|---|---|
| Authorization | `GET https://app.alienmail.io/api/oauth/authorize` |
| Token | `POST https://app.alienmail.io/api/oauth/token` |
| Registration | `POST https://app.alienmail.io/api/oauth/register` |
| Revocation | `POST https://app.alienmail.io/api/oauth/revoke` |

Read the addresses from the metadata in your code instead of hard-coding them.

### 2. Identify your app [#2-identify-your-app]

Your app needs a `client_id`. There are two ways to get one, and neither needs an Alienmail account or an approval from us.

<Tabs items={["Register (most apps)","Client ID metadata document"]}>
<Tab value="Register (most apps)">
Register once and keep the `client_id` you get back (dynamic client registration, RFC 7591):

```bash
curl https://app.alienmail.io/api/oauth/register \
  -H "Content-Type: application/json" \
  -d '{
    "client_name": "My App",
    "redirect_uris": ["https://myapp.example.com/oauth/callback"],
    "token_endpoint_auth_method": "none"
  }'
```

```json
{
  "client_id": "amc_4fJ2…",
  "client_id_issued_at": 1795305600,
  "client_name": "My App",
  "redirect_uris": ["https://myapp.example.com/oauth/callback"],
  "token_endpoint_auth_method": "none",
  "grant_types": ["authorization_code", "refresh_token"],
  "response_types": ["code"],
  "scope": "mcp:read mcp:write"
}
```

`token_endpoint_auth_method` decides the kind of client:

- `none`: a public client, for apps that can't keep a secret (desktop, mobile, CLI, browser). It must use PKCE.
- `client_secret_basic` (the default when you leave it out) or `client_secret_post`: a client with a secret, for a server. The answer then also carries a `client_secret`, shown this once. Store it; Alienmail keeps only a hash.

A registration that nobody uses to connect is deleted after 30 days. Once one person allows your app, it is kept.
</Tab>

<Tab value="Client ID metadata document">
Host a small JSON document at an `https` address and use that address as your `client_id`. Nothing to register and nothing to store.

```json
{
  "client_id": "https://myapp.example.com/oauth/client.json",
  "client_name": "My App",
  "redirect_uris": ["https://myapp.example.com/oauth/callback"],
  "token_endpoint_auth_method": "none"
}
```

Rules for the document:

- The address is `https`, has a path, and has no port, query or fragment.
- `client_id` in the document is exactly the address it is served from.
- It is served as `application/json`, without a redirect, in at most 5 KB and within 5 seconds.
- It is a public client: `token_endpoint_auth_method` is `none` (or left out) and there is no secret. Use PKCE.

Alienmail reads the document again about once a day, so a change to your redirect URIs can take that long to apply.
</Tab>
</Tabs>

**Redirect URIs.** List 1 to 10. Each must be one of:

- an `https://` address;
- `http://localhost`, `http://127.0.0.1` or `http://[::1]` for an app on the person's own computer. The port may differ from the one you registered;
- your app's own scheme, such as `myapp://oauth/callback`.

A redirect URI can't contain a fragment (`#`), a user name or a password. The address you send later must match a registered one exactly.

### 3. Send the person to Alienmail [#3-send-the-person-to-alienmail]

Make a PKCE pair first: a random `code_verifier` of 43 to 128 characters (`A-Z`, `a-z`, `0-9`, `-`, `.`, `_`, `~`), and a `code_challenge` that is the base64url SHA-256 of it. Keep the verifier with the person's session.

```js
import crypto from 'node:crypto';

const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
const state = crypto.randomBytes(16).toString('base64url');
```

Then open this address in the person's browser:

```txt
https://app.alienmail.io/api/oauth/authorize
  ?response_type=code
  &client_id=amc_4fJ2…
  &redirect_uri=https%3A%2F%2Fmyapp.example.com%2Foauth%2Fcallback
  &scope=mcp%3Aread%20mcp%3Awrite
  &state=…
  &code_challenge=…
  &code_challenge_method=S256
```

| Parameter | Notes |
|---|---|
| `response_type` | Always `code`. |
| `client_id` | From step 2. |
| `redirect_uri` | One you registered. Can be left out only when you registered exactly one. |
| `scope` | `mcp:read`, or `mcp:read mcp:write`. Left out means both. See [Scopes](#scopes). |
| `state` | Your own random value, up to 2,048 characters. Check that it comes back unchanged. |
| `code_challenge`, `code_challenge_method` | PKCE. The method is always `S256`. Required for public clients. |
| `resource` | Optional. If you send it, it must be `https://app.alienmail.io/api/mcp`. |

The person signs in to Alienmail if they aren't already, picks the workspace your app may use, sees what it will be able to do, and chooses **Allow** or **Cancel**. They can switch off making changes, in which case your app gets `mcp:read` only. The screen stays valid for 15 minutes.

Alienmail then sends the browser back to your redirect URI:

```txt
https://myapp.example.com/oauth/callback?code=…&state=…&iss=https%3A%2F%2Fapp.alienmail.io
```

Check that `state` is yours and `iss` is `https://app.alienmail.io`. If the person chose Cancel, you get `error=access_denied` instead of `code`.

<Callout type="info" title="A broken request shows an error page">
If the request itself is wrong (unknown `client_id`, a redirect URI you didn't register, missing PKCE), Alienmail shows the person an error page that names the problem. It does not send them back to your app, so test the request in a browser while you build.
</Callout>

### 4. Get the tokens [#4-get-the-tokens]

Exchange the code within 5 minutes. A code works once.

```bash
curl https://app.alienmail.io/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d grant_type=authorization_code \
  -d code=CODE_FROM_THE_REDIRECT \
  -d redirect_uri=https://myapp.example.com/oauth/callback \
  -d client_id=amc_4fJ2… \
  -d code_verifier=YOUR_CODE_VERIFIER
```

A client with a secret also sends it: as HTTP Basic (`client_id` as the user name, the secret as the password) or as `client_secret` in the body. Send it one way, not both.

```json
{
  "access_token": "amoa_…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "amor_…",
  "scope": "mcp:read mcp:write"
}
```

`scope` is what the person allowed, which can be less than you asked for.

<Callout type="warn" title="Use a code once">
Sending a code a second time, or with the wrong `code_verifier` or `redirect_uri`, cancels the connection it made. The person then has to allow your app again.
</Callout>

### 5. Call the MCP server [#5-call-the-mcp-server]

Send the access token in the `Authorization` header, on every request, exactly as an API key is sent in [Talk to the server](#talk-to-the-server):

```bash
curl https://app.alienmail.io/api/mcp \
  -H "Authorization: Bearer amoa_…" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```

Never put the token in the URL. A token in the URL is refused.

### 6. Refresh the access token [#6-refresh-the-access-token]

An access token lasts one hour. When it runs out, the MCP server answers `401` with `error="invalid_token"` in `WWW-Authenticate`. Get a new one with the refresh token:

```bash
curl https://app.alienmail.io/api/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d grant_type=refresh_token \
  -d refresh_token=amor_… \
  -d client_id=amc_4fJ2…
```

The answer has the same shape as in step 4.

- **Public clients get a new refresh token every time.** Save the new one and throw the old one away. The old one still works for 60 seconds, so a retry after a lost response is safe. Using an old one after that cancels the connection, because it looks like a stolen token.
- Clients with a secret keep the same refresh token.
- A refresh token lasts 90 days from its last use. An app that refreshes at least once in 90 days stays connected; after that the person allows it again.

### 7. Disconnect [#7-disconnect]

When a person disconnects Alienmail in your app, revoke the refresh token. This ends the whole connection:

```bash
curl https://app.alienmail.io/api/oauth/revoke \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d token=amor_… \
  -d client_id=amc_4fJ2…
```

The answer is `200` whether or not the token was still valid. The person can also disconnect your app themselves in **Workspace settings → Integrations → Connected apps**.

## Scopes [#scopes]

| Scope | What the app gets |
|---|---|
| `mcp:read` | The tools that only read: campaigns, leads, templates, mailboxes, credits and analytics. |
| `mcp:write` | Every tool the person's role allows, including the ones that create, change, delete and start. It always comes with `mcp:read`. |

## What a connection can do [#what-a-connection-can-do]

- It works in **one workspace**, the one the person picked. To work with another workspace, the person connects again and picks it; each is its own connection with its own tokens.
- It acts as that person, with **their role**. If their role changes, what your app can do changes with it on the next call.
- `tools/list` already leaves out the tools the connection can't call. Calling one anyway returns a tool error.
- `get_user_profile`, `list_workspaces` and `create_workspace` are not available to connections or API keys.
- If the same person connects your app to the same workspace again, the new connection replaces the old one and the old tokens stop working.

## When a connection stops working [#when-a-connection-stops-working]

The MCP server answers `401` and the token endpoint answers `invalid_grant` when:

- the person, or someone who manages the workspace, disconnected your app;
- the person changed or reset their Alienmail password (this ends all their connections, in every workspace);
- the person left the workspace, or their account was suspended or deleted;
- the workspace was archived or deleted;
- your app didn't refresh for 90 days;
- an old refresh token or a used code was sent again.

On a `401`, refresh once. If the refresh answers `invalid_grant`, the connection is gone: drop the stored tokens and send the person through [step 3](#3-send-the-person-to-alienmail) again.

## Errors [#errors]

**OAuth endpoints** (register, token, revoke) answer in the standard OAuth shape:

```json
{ "error": "invalid_grant", "error_description": "The code is invalid or expired." }
```

| Status | `error` | Why |
|---|---|---|
| `400` | `invalid_request` | A parameter is missing, repeated, or sent in the wrong format. |
| `400` | `invalid_grant` | The code or refresh token is wrong, expired, used, or the connection ended. |
| `400` | `invalid_scope` | A refresh asked for a scope the person didn't allow. |
| `400` | `invalid_target` | `resource` is not the MCP server's address. |
| `400` | `unsupported_grant_type` | `grant_type` is not `authorization_code` or `refresh_token`. |
| `400` | `invalid_redirect_uri`, `invalid_client_metadata` | Registration was refused. The description says which field. |
| `401` | `invalid_client` | Unknown `client_id`, a wrong or missing secret, or a secret sent by a public client. |
| `429` | `rate_limited` | Too many requests. Wait for `Retry-After` seconds. |

**The MCP server** answers `401` for a missing or refused token, with the `WWW-Authenticate` header shown above.

**Tool calls** that fail still answer `200`, with `isError` set in the result:

```json
{ "jsonrpc": "2.0", "id": 3, "result": { "isError": true, "content": [{ "type": "text", "text": "Error executing tool start_campaign: …" }] } }
```

This covers a tool the role or scope doesn't allow, a wrong argument, a campaign, lead or mailbox that doesn't exist or can't change right now, and the tool-call limit (the text then says how long to wait). When Alienmail refused the request, the text starts with its status, for example `Status: 404 Not Found`, followed by the answer.

## Limits [#limits]

| What | Limit |
|---|---|
| Tool calls | 60 per minute and 2,000 per day for each API key or connection |
| Open SSE streams | 5 for each API key or connection |
| Token requests | 600 per minute per IP address |
| Authorization requests | 60 per minute per IP address |
| Registrations | 300 per hour per IP address |
| Requests with a wrong API key | 30 per minute per IP address |

Over a limit, the endpoint answers `429` with `Retry-After`. Two differ: a tool call returns a tool error that says how long to wait, and the authorization endpoint shows the person an error page. Register your app once and reuse the `client_id`; don't register on every sign-in.

## Checklist [#checklist]

- Read the endpoints from the metadata documents.
- Use PKCE with `S256`, and check `state` and `iss` on the way back.
- Store tokens on your server or in the device's secure storage, never in a URL or a log.
- Save the new refresh token after every refresh.
- Treat `invalid_grant` as "connect again", and tell the person.
- Ask for `mcp:read` only if your app never changes anything.