# MCP OAuth2 — Guide

What was built to connect Tiledesk AI agents to MCP servers protected by OAuth2, and which use cases it covers.

Italian version: [mcp-oauth2-it.md](mcp-oauth2-it.md). Detailed design: [superpowers/specs/2026-11-10-mcp-oauth2-design.md](superpowers/specs/2026-11-10-mcp-oauth2-design.md).

## 1. In short

Many MCP servers (Google Workspace, Google Cloud, SaaS products, internal company servers) do not accept a static API key: they require OAuth2. The user who owns the data must approve access on the provider's page, and the client receives an access token that expires (usually after one hour) plus a refresh token to get new ones.

With this feature **tiledesk-server is the OAuth client** for the project:

- an admin connects the MCP server once, approving access on the provider's page;
- the server stores the tokens **encrypted** in the database and **refreshes** them when they are about to expire;
- the chatbot (tybot), when an AI Prompt action uses that MCP server, asks the server for a valid access token and sends it as `Authorization: Bearer …`.

Tokens never reach the browser and are never written into the project integrations.

## 2. Use cases

| # | Use case | How |
|---|---|---|
| 1 | MCP server that follows the MCP Authorization spec (discovery + dynamic client registration) | Mode **`mcp`**: the admin types only the MCP server URL; the server discovers the OAuth provider and registers itself as a client |
| 2 | Google MCP servers (Calendar, Gmail, Drive, BigQuery, Cloud Run, …) | Mode **`google`**: one Google OAuth client for the whole installation, configured from env; scopes are optional for the known Google MCP servers (the server uses the ones documented by Google), required for the others |
| 3 | Any OAuth2 provider without discovery | Mode **`manual`**: the admin enters authorization URL, token URL, client ID and secret, scopes |
| 4 | AI agent using an OAuth MCP server during a conversation | tybot asks `GET /mcp/oauth/connections/:id/token` with the bot JWT and sends the Bearer to the MCP server through the LLM backend |
| 5 | Admin lists tools and saves the server from the dashboard | `/mcp/connect`, `/mcp/tools` and `/mcp/servers` accept `oauth: { connection_id }` |
| 6 | Access token expired | Automatic refresh when the token is requested (lazy) and, optionally, periodic refresh by the scheduler |
| 7 | Access revoked by the user at the provider, or refresh token expired | The connection becomes `needs_reauth`; the AI Prompt action fails with "MCP server … needs to be reconnected"; the admin reconnects |
| 8 | Disconnect a server | `DELETE` of the connection: revocation at the provider, deletion, `oauth` removed from the integration |

Not covered yet: OAuth on **native** MCP servers (Tiledesk catalog), per-end-user tokens (every conversation of the project uses the connection authorized by the admin), the Design Studio UI.

## 3. Architecture

```mermaid
flowchart LR
  subgraph Browser
    D[Dashboard<br/>Integrations → MCP]
    P[Provider consent page]
  end
  subgraph Tiledesk
    S[tiledesk-server<br/>OAuth client]
    DB[(MongoDB<br/>mcp_oauth_connections<br/>tokens encrypted)]
    R[(Redis<br/>state, refresh lock)]
    T[tybot<br/>AI Prompt action]
    L[LLM backend]
    SC[scheduler-service]
  end
  subgraph External
    AS[OAuth provider<br/>Google / MCP auth server / other]
    M[MCP server]
  end

  D -- "authorize, connections, tools" --> S
  D -. opens .-> P
  P -- consent --> AS
  AS -- "redirect /oauth2/mcp/callback" --> S
  S <-- "code → tokens, refresh" --> AS
  S --- DB
  S --- R
  T -- "GET …/token (bot JWT)" --> S
  T -- "servers + Bearer" --> L
  L -- "MCP calls + Bearer" --> M
  S -- "connect / list tools + Bearer" --> M
  SC -- "POST /webhook/mcp-oauth/refresh" --> S
```

| Component | Role | Status |
|---|---|---|
| tiledesk-server | OAuth flow, encrypted storage, refresh, token endpoint, management API, scheduler webhook | Done, deployed on stage |
| tiledesk-chatbot (tybot) | Reads `oauth.connection_id` from the integration, gets the token, sends the Bearer | Implementation plan delivered |
| tiledesk-scheduler-service | `mcpOAuthRefresh` target calling the refresh webhook | Implementation plan delivered |
| tiledesk-dashboard | Authentication selector, popup flow, connection status, reconnect | Implementation plan delivered |

## 4. Server components

| File | Content |
|---|---|
| `models/mcpOAuthConnection.js` | Collection `mcp_oauth_connections`: one connection per project and MCP server URL; public view without secrets (`toPublic`) |
| `services/mcpOAuthService.js` | Authorization start and callback, token exchange, lazy refresh with lock, refresh of due connections, revocation |
| `services/mcpOAuthDiscovery.js` | Mode `mcp`: Protected Resource Metadata (RFC 9728), Authorization Server Metadata (RFC 8414 / OIDC), Dynamic Client Registration (RFC 7591) |
| `utils/mcpOAuthCrypto.js` | AES-256-GCM encryption of tokens and client secrets (`v1:` format) |
| `utils/mcpOAuthPkce.js` | PKCE S256 verifier/challenge and random `state` |
| `utils/outboundUrlGuard.js` | Blocks calls to non-https URLs and to private/loopback addresses (SSRF) |
| `routes/mcpOAuth.js` | `/:projectid/mcp/oauth/*`: authorize, connections, refresh, delete, token |
| `routes/mcpOAuthCallback.js` | Public `GET /oauth2/mcp/callback` |
| `routes/webhook.js` | `POST /webhook/mcp-oauth/refresh` for the scheduler |
| `services/mcpService.js` | MCP calls with `oauth.connection_id`: adds the Bearer, retries once after a 401 with a forced refresh |

## 5. Connecting a server (authorization flow)

```mermaid
sequenceDiagram
  autonumber
  actor A as Admin
  participant D as Dashboard
  participant S as tiledesk-server
  participant AS as OAuth provider
  participant M as MCP server

  A->>D: Connect (mode mcp / google / manual)
  D->>S: POST /:project/mcp/oauth/authorize
  opt mode mcp
    S->>M: initialize without token → 401 + resource_metadata
    S->>AS: metadata discovery + client registration (DCR)
  end
  S->>S: state + PKCE in Redis (10 min, single use)
  S-->>D: authorization_url, connection_id
  D->>AS: opens authorization_url (popup)
  A->>AS: login + consent
  AS->>S: GET /oauth2/mcp/callback?code&state
  S->>AS: code + code_verifier → access + refresh token
  S->>S: tokens encrypted in MongoDB, status active
  S-->>A: "Connected" page (or redirect to return_url)
  D->>S: POST /mcp/tools { url, oauth: { connection_id } }
  S->>M: tools/list + Bearer
  D->>S: save server with oauth.connection_id
```

The saved integration entry holds only a reference:

```json
{ "name": "Google Calendar", "url": "https://calendarmcp.googleapis.com/mcp/v1",
  "transport": "streamable_http", "tools": [ ... ],
  "oauth": { "connection_id": "6731f0…", "mode": "google" } }
```

## 6. Using the token during a conversation

```mermaid
sequenceDiagram
  autonumber
  participant U as End user
  participant T as tybot (AI Prompt)
  participant S as tiledesk-server
  participant AS as OAuth provider
  participant L as LLM backend
  participant M as MCP server

  U->>T: message
  T->>S: GET /integration/name/mcp
  T->>S: GET /mcp/oauth/connections/:id/token (bot JWT)
  alt token valid for more than 5 minutes
    S-->>T: access_token
  else expiring or expired
    S->>AS: grant_type=refresh_token (Redis lock)
    AS-->>S: new access token (and refresh token, if rotated)
    S-->>T: new access_token
  end
  T->>L: prompt + MCP servers with Authorization: Bearer
  L->>M: tools/call + Bearer
  M-->>L: result
  L-->>T: answer
  T-->>U: answer
```

- The token endpoint answers only to **bot or subscription** credentials of the same project: an admin JWT gets 403, so tokens never reach the dashboard.
- tybot keeps the token in memory until 60 seconds before it expires.
- If the connection must be authorized again (409 `needs_reauth`), the action fails like a missing integration: `flowError` "MCP server … needs to be reconnected", then the action's false branch.

## 7. Token refresh

Two mechanisms, both on the server:

1. **Lazy (always active).** Every token request checks the expiry. If the access token expires within 5 minutes it is refreshed, otherwise the stored one is returned. A Redis lock makes sure that concurrent requests, even from different pods, cause a single refresh. A 401 from the MCP server triggers one forced refresh and a retry.
2. **Periodic (optional).** The scheduler calls `POST /webhook/mcp-oauth/refresh` with `{ within_seconds }`: the server refreshes the active connections that expire within that window. It is useful for connections that nobody uses for days (some providers expire unused refresh tokens) and to find revoked connections before a conversation hits them. The lazy mechanism alone is enough for the chatbot to work.

```mermaid
stateDiagram-v2
  [*] --> pending: authorize
  pending --> active: callback ok
  pending --> pending: provider error (last_error)
  active --> active: refresh ok
  active --> needs_reauth: invalid_grant (revoked / expired)
  needs_reauth --> active: new authorize + consent
  active --> [*]: DELETE (revoke + delete)
  needs_reauth --> [*]: DELETE
```

A temporary provider error (network, 5xx) does not change the status: the request answers 503 and the next one tries again.

## 8. API

Base: `/:project_id/mcp/oauth` (header `Authorization: JWT …`). Every route answers 503 `not_configured` when the feature is not configured.

| Method and path | Who | Purpose |
|---|---|---|
| `POST /authorize` | admin | Starts the flow. Body `{ mode, server_url, name?, scopes?, manual?, return_url? }` → `{ authorization_url, connection_id }` |
| `GET /connections` | admin | List of connections (no secrets) |
| `GET /connections/:id` | admin | One connection: `status`, `expires_at`, `last_error`, `granted_scopes`, … |
| `POST /connections/:id/refresh` | admin | Forces a refresh |
| `DELETE /connections/:id` | admin | Revokes at the provider, deletes, removes `oauth` from the integration |
| `GET /connections/:id/token` | bot, subscription | `{ access_token, token_type, expires_at }` |

Other routes:

| Method and path | Purpose |
|---|---|
| `GET /oauth2/mcp/callback` | Provider redirect (public, protected by the single-use `state`) |
| `POST /webhook/mcp-oauth/refresh` | Scheduler. Header `x-auth-token`. Body `{ within_seconds }` (60..86400, default 900) or `{ connection_id }` |
| `POST /:project_id/mcp/connect`, `/tools`, `/servers` | Accept `oauth: { connection_id }` for custom servers |

Main errors: 400 invalid body, discovery not supported, connection used for another URL; 403 admin on the token endpoint; 404 connection missing or of another project; 409 `needs_reauth`; 502/503 provider unreachable.

## 9. Configuration

| Variable | Required | Purpose |
|---|---|---|
| `MCP_OAUTH_ENCRYPTION_KEY` | yes | 32 bytes in base64 (`openssl rand -base64 32`). Same value on every replica and stable over time: changing it makes the stored tokens unreadable |
| `MCP_OAUTH_REDIRECT_BASE_URL` | yes (fallback `API_URL`) | Public API URL, e.g. `https://stage.eks.tiledesk.com/api`. Redirect URI = `<base>/oauth2/mcp/callback` |
| `MCP_OAUTH_GOOGLE_CLIENT_ID`, `MCP_OAUTH_GOOGLE_CLIENT_SECRET` | for `google` | Google OAuth client of type "Web application" |
| `MCP_OAUTH_REFRESH_TOKEN` | for the scheduler | Shared secret of the refresh webhook (same value on the scheduler worker) |
| `MCP_OAUTH_RETURN_ORIGINS` | only with `return_url` | Origins allowed for the redirect after the callback. The popup flow of the dashboard does not need it |
| `MCP_OAUTH_ALLOW_INSECURE_URLS` | never in production | `true` allows `http://` and private addresses: local development only |

### Google setup

1. Google Cloud project: enable the API of the service and its MCP service (e.g. `calendar-json.googleapis.com` and `calendarmcp.googleapis.com`; for Google Cloud servers `gcloud beta services mcp enable <service>`).
2. Google Auth Platform: consent screen (in "Testing", add the test users), scopes in Data Access.
3. Client of type **Web application**, redirect URI exactly `<MCP_OAUTH_REDIRECT_BASE_URL>/oauth2/mcp/callback`, **"Use this client for an AI-powered agent"** selected (required by the Google Workspace MCP servers).
4. Client ID and secret in the two env variables, restart the pods.

In "Testing" status Google refresh tokens last 7 days. Sensitive or restricted scopes (Gmail, Drive) need Google verification before production.

## 10. Examples

**Google Calendar**

```json
POST /:project_id/mcp/oauth/authorize
{
  "mode": "google",
  "server_url": "https://calendarmcp.googleapis.com/mcp/v1",
  "name": "Google Calendar"
}
```

`scopes` can be omitted for the Google MCP servers listed in `services/mcpOAuthGoogleScopes.js` (Gmail, Drive, Docs, Sheets, Slides, Calendar, Chat, People, Classroom, BigQuery): the server uses the scopes documented by Google, here the three read-only Calendar scopes. Scopes sent in the body replace the defaults, for example `"scopes": ["https://www.googleapis.com/auth/calendar.events"]` for write access. Any other Google URL without `scopes` answers 400. The same scopes must be added in Google Auth Platform → Data Access.

**MCP server with discovery**

```json
{ "mode": "mcp", "server_url": "https://mcp.example.com/mcp", "name": "Example" }
```

**Manual provider**

```json
{
  "mode": "manual",
  "server_url": "https://mcp.example.com/mcp",
  "scopes": ["read"],
  "manual": {
    "authorization_endpoint": "https://auth.example.com/authorize",
    "token_endpoint": "https://auth.example.com/token",
    "client_id": "abc",
    "client_secret": "…"
  }
}
```

Then, in all cases: open `authorization_url`, approve, and use the `connection_id` in `/mcp/tools` and `/mcp/servers`. A Postman collection for these calls is in `postman/import/` (local, not committed yet).

## 11. Security

- Authorization code + **PKCE S256** always; `state` random, single use, 10 minutes, bound to project and user.
- Access tokens, refresh tokens and client secrets **encrypted at rest** (AES-256-GCM); never returned by the management API; redacted in the logs.
- The integration holds only `connection_id`: tokens never end up in the integration cache or in the dashboard.
- The Bearer is sent only to the URL the connection was authorized for: using a connection with another server URL answers 400.
- Outbound URL guard: https only, no private, loopback or link-local addresses, no redirects, timeouts and response size limits.
- `return_url` allowed only towards origins in `MCP_OAUTH_RETURN_ORIGINS`.
- Scheduler webhook protected by a shared token compared in constant time.

## 12. Testing

- Automated: mocha tests `test/mcpOAuthUtils`, `mcpOAuthDiscovery`, `mcpOAuthService`, `mcpOAuthRoute`, `mcpServiceOAuth` (providers and MCP servers mocked with nock, real Mongo and Redis).
- End to end, locally: [modelcontextprotocol/example-remote-server](https://github.com/modelcontextprotocol/example-remote-server) (`npm run dev:internal`, port 3232) with `MCP_OAUTH_ALLOW_INSECURE_URLS=true`. On a public URL it must be started with `BASE_URI=<public URL>`, otherwise its metadata points to `localhost`.
- Stage: mode `mcp` with the reference server behind a public tunnel, mode `google` with a Google Cloud client.
