> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runlayer.com/llms.txt
> Use this file to discover all available pages before exploring further.

# OAuth for Deployed MCP Servers

> Build custom MCP servers with OAuth that authenticate users against third-party services like Slack or Google.

# OAuth for Deployed MCP Servers

When you build a custom MCP server that needs to call third-party APIs (e.g., Slack, Zendesk, Google) on behalf of users, someone has to run an OAuth flow with that service and hold the resulting tokens. On Runlayer Deploy that is either Runlayer, using an OAuth client you enter on the connector, or your server, hosting its own OAuth authorization server. This guide explains the dual-auth architecture, the two modes, and how to persist tokens across container restarts.

## Dual-Auth Architecture

There are two completely independent OAuth flows involved when an agent uses your deployed MCP server:

```mermaid theme={null}
sequenceDiagram
    participant Agent as Agent / Client
    participant MCP as Your Deployed MCP Server
    participant Vendor as Third-Party API (e.g., Slack)

    Note over Agent,MCP: Auth 1 — Runlayer Platform Auth
    Agent->>MCP: Every request includes Runlayer Bearer token
    MCP->>MCP: Identify user from Bearer token

    Note over MCP,Vendor: Auth 2 — Vendor OAuth (one-time setup per user, run by Runlayer or by your server)
    MCP->>Vendor: Redirect user to vendor OAuth consent
    Vendor-->>MCP: Authorization code
    MCP->>Vendor: Exchange code for access + refresh tokens
    MCP->>MCP: Store tokens keyed by user identity

    Note over Agent,Vendor: Subsequent tool calls
    Agent->>MCP: Tool call + Runlayer Bearer token
    MCP->>MCP: Look up stored vendor token for this user
    MCP->>Vendor: API call using vendor token
    Vendor-->>MCP: API response
    MCP-->>Agent: Tool result
```

### Auth 1 — Runlayer Platform Auth (Agent → MCP Server)

The agent authenticates to your MCP server using a **Runlayer Bearer token**. This token comes from Runlayer platform auth (e.g., Rippling SSO → Runlayer). The agent stores this token locally and sends it in the `Authorization` header on every request to `/mcp`.

This token identifies **who** is calling. Your server uses it to look up the right vendor tokens for that user.

### Auth 2 — Vendor OAuth (Runlayer or MCP Server → Third-Party)

When a user first connects, someone runs an OAuth flow with the vendor (Slack, Zendesk, Google, etc.), receives an access token and refresh token, and stores them keyed by the user's identity. On later tool calls the stored token is used to call the vendor API on the user's behalf.

On Runlayer Deploy that someone is one of:

* **Runlayer**, using a **Pre-registered Client** you enter on the connector's **Settings** tab. Runlayer stores the tokens and sends the user's vendor access token to your server as the Bearer token on `/mcp`.
* **Your MCP server**, acting as a **container-hosted authorization server** with its own `/.well-known/oauth-authorization-server`, `/authorize`, and `/token` endpoints. Your server stores the tokens.

[Connecting OAuth to Runlayer](#connecting-oauth-to-runlayer) covers how to set up each.

**The agent never sees the vendor token.** It's stored and used entirely server-side.

## DynamoDB Storage

Runlayer can provision a DynamoDB table for your deployed container. This is useful for any persistent storage your server needs — OAuth tokens, user preferences, cached data, etc.

In your `runlayer.yaml`, enable it with:

```yaml theme={null}
infrastructure:
  enable_db: true
```

This automatically:

* Creates a DynamoDB table with server-side encryption
* Sets up IAM permissions for your container
* Injects `DB_TABLE_NAME`, `DB_TABLE_REGION`, and `TOKEN_ENCRYPTION_KMS_KEY_ID`

`TOKEN_ENCRYPTION_KMS_KEY_ID` contains the ARN of a customer-managed KMS key with automatic rotation. The deployment task role can use it for `kms:GenerateDataKey` and `kms:Decrypt`.

> [!NOTE]
>
> This section describes Runlayer-hosted (ECS). On self-hosted Kubernetes, `enable_db` instead provisions [ExtendDB](https://github.com/extenddb/extenddb) on the instance's Postgres — same `DB_TABLE_NAME`/`DB_TABLE_REGION` contract, but **no `TOKEN_ENCRYPTION_KMS_KEY_ID`** in v1, and your SDK must support [service-specific endpoint env vars](https://docs.aws.amazon.com/sdkref/latest/guide/feature-ss-endpoints.html) (botocore ≥ 1.31.0 / boto3 ≥ 1.28.0). All `enable_db` MCPs on an instance share one SigV4 key, so one compromised token-store MCP can read or overwrite another's stored OAuth tokens until per-MCP keys land. On Kubernetes the operator mounts keys/CA as AWS profile **`extenddb`** (`EXTENDDB_AWS_PROFILE`); IRSA on the same MCP ServiceAccount is allowed for other AWS APIs. The Dynamo client must follow `EXTENDDB_AWS_PROFILE` when set (default chain when unset — ECS unchanged). See [Deploy auth](https://docs.runlayer.com/platform-deploy.md#extenddb-auth) for details.

When `TOKEN_ENCRYPTION_KMS_KEY_ID` is set, `DynamoDBTokenStore` uses the key automatically to encrypt sensitive token fields with AES-256-GCM. `TOKEN_ENCRYPTION_MODE` selects how strictly: `bridge` (the default) also keeps a plaintext copy so older connector builds can still read the record, while `encrypted` requires ciphertext for all reads and writes and fails closed if a record cannot be decrypted. Runlayer sets `encrypted` on newly created deployments; deployments created earlier stay on `bridge` until their tables hold no plaintext-only records. Passing `mode` in code takes effect only when `TOKEN_ENCRYPTION_MODE` is unset; if both are set to different values, the store fails at startup.

> [!NOTE]
>
> DynamoDB server-side encryption applies to the whole table. Application-layer encryption applies only when your code uses the KMS key; custom token stores must encrypt sensitive fields before writing them.

The table uses a composite key (`pk` string + `sk` string) with TTL support. Example usage:

> [!WARNING]
>
> The example below demonstrates DynamoDB access only. Do not store production OAuth credentials this way without application-layer encryption; use the Runlayer auth framework or an equivalent envelope-encryption implementation.

```python theme={null}
import os
import time
import boto3

dynamodb = boto3.resource("dynamodb", region_name=os.environ["DB_TABLE_REGION"])
table = dynamodb.Table(os.environ["DB_TABLE_NAME"])

def save_tokens(user_id: str, access_token: str, refresh_token: str, expires_in: int):
    table.put_item(Item={
        "pk": user_id,
        "sk": "tokens",
        "access_token": access_token,
        "refresh_token": refresh_token,
        "expires_at": int(time.time()) + expires_in,
        "ttl": int(time.time()) + (90 * 86400),  # Auto-expire after 90 days
    })

def load_tokens(user_id: str) -> dict | None:
    resp = table.get_item(Key={"pk": user_id, "sk": "tokens"})
    return resp.get("Item")
```

> [!WARNING]
>
> Once `enable_db` is set to `true` and deployed, it **cannot be disabled**. See [Deploy docs](https://docs.runlayer.com/platform-deploy.md) for details.

## Connecting OAuth to Runlayer

Both modes start with the vendor: register an OAuth app with it (Slack, Zendesk, Google, etc.) and note the client ID, client secret, and the scopes your server needs. In both modes, register `https://<your-runlayer-host>/oauth/callback` as the redirect URI with the vendor. Your container gets the same value as the `RUNLAYER_OAUTH_CALLBACK_URL` environment variable.

Then pick a mode.

### Pre-registered Client: Runlayer runs the vendor flow

Use this when the vendor issues you a fixed client ID and secret and you want no OAuth code in your container. Zendesk, for example, publishes no OAuth discovery metadata and offers no dynamic client registration, so this is the mode that fits it.

Your server hosts no OAuth endpoints, needs no `enable_db`, and needs no `service.expose`. It has two jobs: reject requests to `POST /mcp` that carry no valid vendor token (respond `401` with a `WWW-Authenticate: Bearer` header), and use the token it does receive to call the vendor API.

The client lives on the connector, not in `runlayer.yaml`:

1. Run `runlayer deploy init` if you have not already. This creates the connector in `Draft`.
2. In Runlayer, open the connector and go to its **Settings** tab.
3. Set **Authentication** to **OAuth 2.1** and **Registration** to **Pre-registered Client**.
4. Enter the **Client ID** and **Client Secret**, the vendor's **Authorization URL** and **Token URL**, and the **OAuth Scopes** your server needs.
5. Save, then run `runlayer deploy`.

Until the client is entered, every deploy leaves the connector in `Draft`: Runlayer's connection test reaches your server, gets a `401`, and has no OAuth client to sign a user in with, so it does not activate the connector. Once the client is saved, the next deploy that succeeds activates it. You can enter the client before the first deploy or after one that left the connector in `Draft`.

### Container-hosted authorization server: your server runs the vendor flow

Use this when your server needs to control the vendor exchange itself, or when the vendor client secret must stay inside the container.

Your server acts as an OAuth authorization server. It hosts:

* `GET /.well-known/oauth-authorization-server` — discovery metadata, with every URL built from `DEPLOYMENT_URL`
* `GET /authorize` — redirects the user to the vendor's consent page
* `POST /token` — exchanges authorization codes and refreshes tokens
* `POST /register` — optional. Returns the client Runlayer should use when talking to your server. Without it, an admin enters that client on the connector's **Settings** tab instead.
* Token storage in DynamoDB (`enable_db: true`)

Runlayer discovers your metadata, sends the user's browser to your deployment's `/authorize`, and calls your `/token`. Your server owns the credential exchange with the vendor and the per-user tokens. The vendor client goes in `runlayer.yaml` as env vars. This is how Runlayer's built-in Slack, Google Drive, and Gmail connectors work:

```yaml theme={null}
infrastructure:
  enable_db: true

service:
  port: 8000
  path: /mcp
  expose:
    - "/.well-known/*"
    - "/register"
    - "/authorize"
    - "/token"

env:
  GOOGLE_OAUTH_CLIENT_ID: "${GOOGLE_OAUTH_CLIENT_ID}"
  GOOGLE_OAUTH_CLIENT_SECRET: "${GOOGLE_OAUTH_CLIENT_SECRET}"
  GOOGLE_OAUTH_REDIRECT_URIS: "$$RUNLAYER_OAUTH_CALLBACK_URL"
  BASE_URL: "$$DEPLOYMENT_URL"
```

> [!WARNING]
>
> On Runlayer Deploy, Runlayer always sends the user's browser to your deployment's own `/authorize` through the public proxy. It does not follow the `authorization_endpoint` in your discovery document. A container that points its discovery document at the vendor's authorization endpoint and serves no `/authorize` of its own cannot complete a login, and its connector stays in `Draft`. Either serve `/authorize` or use a Pre-registered Client.

### Comparison

| | Pre-registered Client | Container-hosted authorization server |
| - | - | - |
| Who runs the vendor flow | Runlayer | Your server |
| Your server implements | `POST /mcp` only | `/.well-known/*`, `/authorize`, `/token`, optionally `/register` |
| Where the vendor client lives | Connector **Settings** | Env vars in `runlayer.yaml` |
| Token storage | Runlayer | Your server (DynamoDB) |
| `enable_db` needed | No | Yes |
| `service.expose` needed | No | Yes |

## OAuth Expose Paths and Auth Middleware

When your container hosts the authorization server, its OAuth endpoints must be accessible **without** a Bearer token:

| Endpoint | Purpose | Required |
| - | - | - |
| `GET /.well-known/oauth-authorization-server` | OAuth discovery | Yes |
| `GET /authorize` | OAuth authorization redirect | Yes |
| `POST /token` | OAuth token exchange | Yes |
| `POST /register` | Hands Runlayer the client it should use | Optional |
| `POST /revoke` | OAuth token revocation | Optional |

Only list OAuth endpoints your server actually implements. Typical OAuth expose paths are `/.well-known/*`, `/register`, `/authorize`, `/token`, and optionally `/revoke`.

Exposed paths are served on your Runlayer host, so Runlayer removes the user's browser cookies from requests, drops any `Set-Cookie` your server returns, and serves every response with `Content-Security-Policy: sandbox`, which blocks scripts and form submission. Return redirects and JSON from these endpoints, not login or consent pages.

`/mcp` stays authenticated and should not be listed in `service.expose`. Servers that use a Pre-registered Client, and servers without OAuth, host no OAuth endpoints and should not set `service.expose`.

If your auth middleware is applied **globally** (blocking all unauthenticated requests), connector registration will fail because Runlayer can't reach the OAuth discovery routes.

**Fix:** scope your auth middleware to protect `POST /mcp`, and allow only the OAuth routes with `service.expose` in your `runlayer.yaml`:

```yaml theme={null}
service:
  port: 8000
  path: /mcp
  expose:
    - "/.well-known/*"
    - "/register"
    - "/authorize"
    - "/token"
    - "/revoke"
```

## FAQ

> [accordion] Does the agent ever see the vendor token (e.g., Slack token)?
>
> No. The agent only holds a Runlayer Bearer token. The vendor token is stored and used server-side — either by Runlayer (Pre-registered Client) or by your server (container-hosted authorization server).

> [accordion] Are the two OAuth flows related?
>
> No. Runlayer platform auth (SSO → Bearer token) and vendor OAuth (your server → Slack) are completely independent. The Runlayer token identifies the user; the vendor token authorizes API calls.

> [accordion] Why DynamoDB for token storage?
>
> Only needed when your server hosts the authorization server. Deployed containers can restart or scale at any time, so in-memory or file-based storage won't survive. `enable_db: true` gives you persistent storage with no setup.

> [accordion] My deploy succeeded but the connector is still in Draft. What's wrong?
>
> Runlayer's connection test did not pass, so it did not activate the connector. If your vendor issued you a fixed client ID and secret, open the connector's **Settings** tab, choose **Pre-registered Client**, enter the client and the vendor's authorization and token URLs, and deploy again. If your server hosts the authorization server, your auth middleware is probably blocking its endpoints: make sure `/.well-known/oauth-authorization-server`, `/authorize`, and `/token` are listed in `service.expose` and served without a Bearer token.

> [accordion] Can I look at an example?
>
> The Runlayer-built connectors (Slack, Google Drive, Gmail) host their own authorization server: the server runs the vendor flow and stores tokens in DynamoDB. Open-source examples are coming soon.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.