# Central MCP gateway (single sign-on)

One HTTPS address per MCP server for the whole organization, for example
`https://mcp.example.com/jira/mcp`. Coding agents (Claude Code, Codex, Cursor) connect to it like
to any remote MCP server; the first time, they open the browser and the user signs in with the
organization's identity provider (Okta, Entra ID, Keycloak, Google: any OIDC provider). No local
proxy, no key on the laptop.

Every message goes through the same checks as the local proxy: data policy, tool permissions
and pins, the placeholder rule (Q-059), confirmation of tools that need approval (2026-07-28
clients). In addition, **every audit entry names the user** and **tool rules can depend on the
user's groups**.

## How sign-in works

1. The agent calls `https://mcp.example.com/jira/mcp` and gets `401` with the resource metadata
   (RFC 9728). The gateway is the authorization server for its own endpoints (RFC 8414).
2. The agent registers itself (RFC 7591, public client) and starts an authorization-code flow
   with PKCE S256, asking for a token for that one server (RFC 8707). Accepted redirect
   addresses: loopback `http://127.0.0.1|localhost|[::1]` (Claude Code, Codex, the MCP SDKs),
   a native app's own scheme (for example `cursor://...`), and `https` only on the hosts listed
   in `redirect_https_hosts` (empty by default). An open https list would let anyone register
   `https://attacker.example/cb` and send a user a sign-in link whose code, and so the user's
   gateway token, would go to the attacker. Redirect addresses may carry their own query.
3. The gateway sends the browser to the identity provider (OIDC code flow with PKCE and a
   nonce), checks the id_token (signature from the provider's keys, issuer, audience, nonce,
   expiry) and issues its own short-lived token for that server. Refresh tokens rotate, but
   never extend the sign-in: `refresh_ttl_s` (default 30 days) is the total lifetime from the
   IdP sign-in, after which the agent signs in again. Every refresh (hourly with the default
   token lifetime) asks the identity provider again with the provider's own refresh token:
   groups follow the provider, and a user it no longer knows is refused, so removal takes
   effect within `token_ttl_s`. For that the provider must issue a refresh token (usually the
   `offline_access` scope in `oidc.scopes`). Without one nothing can be re-checked and the
   sign-in ends after `unverified_session_ttl_s` (one day by default) instead. Registration and token requests over 16 KiB are refused.
4. Each MCP message carries the user (by default the provider's pseudonymous `sub`; set
   `user_claim: email` for readable audit entries) and the groups to the data plane. The data
   plane accepts these only from a key with the scope `mcp_gateway`.

The agent's token is never sent to the remote server.

### Identity storage and upgrade

Upstream grants and per-user proxy state are keyed by a versioned SHA-256 digest of the
full verified OIDC `(issuer, sub)` pair. `user_claim` selects the audit display value only;
its 128-character display limit does not determine credential ownership. Changing an
email/display claim does not switch grants, and distinct subjects never share grants merely
because their display values have the same prefix.

After upgrading from display-keyed storage, clients must sign in again and reconnect their
upstream OAuth accounts. Older access/refresh tokens, authorization codes and connection
links are refused. Existing encrypted legacy grants are not automatically reassigned or
deleted: a truncated identity cannot be safely migrated to an owner. Stop every old gateway
process before starting the updated version; do not run mixed versions on the same database.
Refresh tokens issued before the total sign-in lifetime existed (Q-084) are refused; the agent
signs in again once.

## Credentials for the remote server

| `auth.type` | What the remote server receives |
|---|---|
| `none` | nothing (public servers, or servers inside the network) |
| `static` | one service credential from an environment variable, the same for all users |
| `oauth` | **the user's own** grant: the first call answers with a link; the user opens it once, signs in at the organization's IdP (usually silent) and then at the vendor, and the grant is stored encrypted (Fernet) for that user. The link only works for the user it was made for (a forwarded link cannot attach someone else's vendor account to it), and the vendor sign-in only completes in the browser that opened the link (a cookie bound to that step) |
| `id-jag` | **enterprise-managed authorization** (SEP-990): no link, no consent screen. The gateway exchanges the user's IdP sign-in for an identity assertion at the IdP (RFC 8693, `requested_token_type` ID-JAG) and presents it to the vendor's authorization server (RFC 7523 jwt-bearer) as a confidential client (`client_id`, `client_secret_env`, and the vendor's `issuer`, required: the secret goes only to that authorization server). The IdP decides who may use which server; the vendor gets no refresh token, the exchange repeats when the token expires |

## Configuration

```yaml
public_url: https://mcp.example.com          # as the agents see it
gateway_url: https://aiguard.internal        # the data plane
key_env: AIGUARD_KEY                         # a key with scopes inspect and mcp_gateway
state_dir: /var/lib/aiguard-mcp              # SQLite: clients, codes, tokens, grants
redirect_https_hosts: []                     # e.g. [vscode.dev] for web-based callbacks
secret_key_file: /run/secrets/mcp-gateway.key  # created on first start if missing
oidc:
  issuer: https://login.example.com
  client_id: aiguard-mcp
  client_secret_env: OIDC_CLIENT_SECRET
  groups_claim: groups                       # put group names into the id_token at the IdP
servers:
  jira: {upstream: "https://mcp.atlassian.example/v1/mcp", auth: {type: oauth}}
  wiki: {upstream: "https://wiki.internal/mcp", auth: {type: static, value_env: WIKI_TOKEN}}
  vendor:
    upstream: "https://mcp.vendor.example/mcp"
    auth: {type: id-jag, client_id: aiguard-gateway, client_secret_env: VENDOR_SECRET,
           issuer: "https://auth.vendor.example"}
```

A server's metadata decides where the sign-in goes, so the gateway checks it: every URL taken
from it must use https and may point to a private, loopback or link-local address only when the
configured `upstream` itself is in such a network (no requests to internal services on behalf
of a remote server). `auth.issuer` pins the vendor's authorization server; it is **required**
whenever `client_secret_env` is set, so a changed or hostile metadata document can never
receive the client secret.

```sh
aiguard key-create --keys keys.yaml --id mcp-gateway --kind service --scope inspect --scope mcp_gateway
AIGUARD_KEY=aig_... OIDC_CLIENT_SECRET=... aiguard mcp gateway --config gateway.yaml --port 8780
```

At the identity provider, register a web application with the redirect address
`<public_url>/oauth/callback`. Put the gateway behind your TLS terminator. Group rules:

```yaml
mcp_tools:
  - {id: finance-export, server: erp, tools: [export_*], groups: [finance], action: allow}
  - {id: no-export, server: erp, tools: [export_*], action: block}
```

## Encryption key and rotation

`secret_key_file` holds one Fernet key per line: the first encrypts, each one decrypts. To
rotate, put a new key on the first line and keep the old one below it, then run
`aiguard mcp gateway --config gateway.yaml --rotate-keys` (re-encrypts every stored grant), then
remove the old line. Keep the file in your secret manager (for example a Kubernetes Secret fed
by Vault or a cloud KMS) rather than on a plain disk.

## Verified

`make mcp-real-e2e`: the official MCP Python SDK's OAuth client (dynamic registration, PKCE,
resource indicator, the same flow Claude Code uses) signs in through the gateway to a synthetic
OIDC provider, with the 2025 and the 2026-07-28 protocol; results are cleaned; every audit entry
names the user; a user connects a remote OAuth server (built from the SDK) once through the link;
an `id-jag` server whose authorization server is the SDK's (it checks the assertion's
signature, type, audience, client, resource and replay) works without any consent screen.
Unit tests (`test_mcp_central.py`) cover single-use codes, PKCE, rotation, token binding to one
server, refused registrations and id_tokens, group rules and that only the gateway key may name
a user.

## Limits

- State is one SQLite file: run exactly one instance with a persistent volume (ADR 0010).
  `deploy/mcp-gateway/docker-compose.yml` does that; there is no Helm chart for the gateway.
  While the instance is down, agents get errors and nothing passes.
- Each user's session state (the placeholders they were shown, tools withdrawn for a changed
  definition) is stored encrypted in the same file and survives a restart. A confirmation
  that was pending during a restart is refused; the agent asks again.
- Stdio servers are not run by the gateway (ADR 0010). To offer one centrally, run it yourself
  as an internal HTTP service (the server's own Streamable HTTP mode or a bridge) and list it
  under `servers` with `auth: none` or `static`; all its users then share that service's
  credentials.
- The gateway is an option for selected customers, not part of the specified product, until
  the release gates of Q-080 pass (ADR 0010).
- 2025-era clients over HTTP cannot be asked to confirm a tool (`require_approval` is refused
  for them, with a message); 2026-07-28 clients can.
- Not yet tested with a commercial identity provider or vendor MCP server.
