# Secure an MCP server with Pontive and agentgateway

> Check Pontive access tokens for an MCP server at agentgateway, which also serves its protected resource metadata.

Source: https://www.pontive.com/docs/sdk/mcp-server-agentgateway

For an MCP server that runs behind [agentgateway](https://agentgateway.dev).
agentgateway checks every request's Pontive access token before the request
reaches your server, serves the server's protected resource metadata (RFC
9728), and shows each caller only the tools its token's scopes allow. MCP
clients such as Claude Code then sign the user in at your Pontive instance on
their own.

```
MCP client ──► agentgateway ──► your MCP server
   │  401 + resource_metadata        (token forwarded, or not: below)
   └──► Pontive (sign-in, consent, token for the API)
```

This uses agentgateway's generic configuration. **Do not set a `provider`
block.** agentgateway's providers (`keycloak`, `auth0`, `okta`, `entra`, …)
make the gateway stand in for an authorization server that lacks parts of the
MCP authorization spec. Pontive has them all: authorization server metadata
(RFC 8414), resource indicators (RFC 8707), and client registration by client
ID metadata documents (CIMD) and dynamic client registration (DCR). Clients
talk to Pontive directly.

Tested with agentgateway v1.7.0. The configuration below runs in Pontive's
conformance suite against a live instance on every run.

## 1. Register the MCP server as an API [#1-register-the-mcp-server-as-an-api]

The API's identifier is the server's **public MCP URL**, the one clients
connect to: the gateway's URL, not your server's internal address. Tokens for
the API carry it in `aud`, and the gateway checks it.

In the dashboard: *APIs* → *New API*, identifier `https://mcp.acme.com/mcp`.
Or with a secret key:

```sh
curl -sS https://api.us.pontive.com/v1/apis \
  -H "Authorization: Bearer $PONTIVE_SECRET_KEY" \
  -H "X-Pontive-Instance-ID: $PONTIVE_INSTANCE_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "identifier": "https://mcp.acme.com/mcp",
    "name": "Acme Files",
    "third_party": true,
    "scopes": [
      { "key": "tool:list_files", "description": "List your files" },
      { "key": "tool:read_file",  "description": "Read a file" }
    ]
  }'
```

**One scope per tool.** Tool import writes them for you from your server's
`tools/list` result: one `tool:<name>` scope per tool, with the tool's
description, which the consent screen then shows. Send the result
(`{ "tools": [...] }`, every page at once). Without `dry_run: false` the
call only returns the diff:

```sh
jq '. + { dry_run: false }' tools-list.json |
  curl -sS https://api.us.pontive.com/v1/apis/$API_ID/scopes/import \
    -H "Authorization: Bearer $PONTIVE_SECRET_KEY" \
    -H "X-Pontive-Instance-ID: $PONTIVE_INSTANCE_ID" \
    -H "Content-Type: application/json" \
    -d @-
```

The gateway rule in step 3 lets a caller list and call a tool only when its
token carries that tool's scope.

**Let MCP clients connect.** Claude, Claude Code, ChatGPT, Cursor and VS Code
are third-party clients: they register themselves (CIMD or DCR) and reach an
API only through the instance's third-party client profile. With
`third_party: true` on the API, turn the admission on and add the API to the
profile (dashboard: *Settings* → *Third-party clients*):

```sh
curl -sS -X PATCH https://api.us.pontive.com/v1/apps/settings \
  -H "Authorization: Bearer $PONTIVE_SECRET_KEY" \
  -H "X-Pontive-Instance-ID: $PONTIVE_INSTANCE_ID" \
  -H "Content-Type: application/json" \
  -d '{ "cimd": "open", "dcr": "on", "profile": { "apis": [{ "api_id": "'"$API_ID"'", "scopes": null }] } }'
```

`profile.apis` replaces the list: include the APIs already in it.

A client registered this way that nobody consents to within 24 hours is
removed, and so is one with no consent and no live refresh token for 90 days.
It registers again the next time a user connects it.

## 2. Find your issuer [#2-find-your-issuer]

Your issuer is your instance's auth domain, e.g.
`https://acme.auth.us.pontive.app`. Its discovery document names the key set:

```sh
curl -s https://acme.auth.us.pontive.app/.well-known/oauth-authorization-server | jq -r .jwks_uri
# https://acme.auth.us.pontive.app/oauth2/jwks.json
```

Pontive serves its keys at `/oauth2/jwks.json`, and from auth-api 1.48.0 at
`<issuer>/.well-known/jwks.json` too, which is agentgateway's default for a
configuration without a provider. `jwks.url` is therefore optional; the example
below keeps it so the key set it verifies against is explicit.

## 3. Configure agentgateway [#3-configure-agentgateway]

```yaml
# config.yaml
# yaml-language-server: $schema=https://agentgateway.dev/schema/config
binds:
- port: 3000
  listeners:
  - routes:
    - name: mcp
      matches:
      - path:
          exact: /mcp
      - path:
          exact: /.well-known/oauth-protected-resource/mcp
      backends:
      - mcp:
          targets:
          - name: files
            mcp:
              host: http://files-mcp.internal:8080/mcp   # your MCP server
      policies:
        cors:
          allowOrigins:
          - "*"
          allowHeaders:
          - authorization
          - content-type
          - mcp-protocol-version
          - mcp-session-id
          exposeHeaders:
          - mcp-session-id
          - www-authenticate
        mcpAuthentication:
          mode: strict
          issuer: https://acme.auth.us.pontive.app
          audiences:
          - https://mcp.acme.com/mcp                     # the API's identifier
          jwks:                                          # optional: defaults to <issuer>/.well-known/jwks.json
            url: https://acme.auth.us.pontive.app/oauth2/jwks.json
          jwtValidationOptions:
            requiredClaims: [exp, iss, aud, sub]
          resourceMetadata:
            resource: https://mcp.acme.com/mcp           # the same identifier
            scopesSupported:
            - tool:list_files
            - tool:read_file
            bearerMethodsSupported:
            - header
            resourceName: Acme Files
        mcpAuthorization:
          rules:
          # A tool is listed and callable only with its tool scope.
          # Pontive's scope claim is one space-separated string.
          - allow: '("tool:" + mcp.tool.name) in jwt.scope.split(" ")'
        # Only when the server behind checks the same token itself (below).
        backendAuth:
          passthrough: {}
```

| Setting | Why |
| --- | --- |
| `matches` | The MCP endpoint and its metadata path. The metadata path is `/.well-known/oauth-protected-resource` plus the identifier's path (RFC 9728 §3.1). agentgateway answers it itself, without a token. |
| `issuer` | Your auth domain, compared with the token's `iss`. |
| `audiences` | The API's identifier. A token Pontive issued for another API, or with no `resource` (its `aud` is then the client's own id), is refused. |
| `jwks.url` | Optional. Pontive's `jwks_uri`; without it agentgateway uses `<issuer>/.well-known/jwks.json`, which serves the same keys. agentgateway fetches and caches them. |
| `requiredClaims` | Pontive access tokens always carry these; requiring them refuses anything else. |
| `resourceMetadata` | The metadata agentgateway serves. With no `provider`, its `authorization_servers` is your `issuer`, so clients go to Pontive. `scopesSupported` should be the API's scopes. |
| `mcpAuthorization` | The tool rule above. Without it, any valid token for the API may call every tool. A rule can use any claim: `jwt.sub`, `jwt.org_id`, `jwt.roles`, `jwt.permissions`. |
| `backendAuth: passthrough` | Forwards the caller's token to your server. Keep it if your server verifies the token too (for example with `@pontive/pontkit-server`'s resource-server middleware, [mcp-server.md](/docs/sdk/mcp-server), configured with the same identifier), or if it reads the caller from the token. Leave it out otherwise. The token's audience is this API, so forwarding it to the server behind the gateway is not token passthrough to another API. |

Pontive's access tokens carry `sub` (`usr_…`, `svc_…` or `agt_…`), `client_id`,
`scope`, `org_id`, `roles` and `permissions`, and `act` when an agent acts for
a user. All are usable in `mcpAuthorization` rules and in agentgateway's
other CEL policies, such as rate limits keyed on `jwt.sub`.

**Session key.** agentgateway encrypts MCP session ids. Set `SESSION_KEY` (32
random bytes as hex, `openssl rand -hex 32`), the same on every replica;
without it agentgateway writes a generated key into `config.yaml`.

## 4. Run it [#4-run-it]

```sh
docker run --rm -p 3000:3000 \
  -e SESSION_KEY="$(openssl rand -hex 32)" \
  -v "$PWD/config.yaml:/config.yaml:ro" \
  cr.agentgateway.dev/agentgateway:v1.7.0 -f /config.yaml
```

Or the release binary: `agentgateway -f config.yaml`. In front of it, your TLS
terminator serves `https://mcp.acme.com`, which must be the origin of the
identifier.

## What the client sees [#what-the-client-sees]

| Request | Answer from agentgateway |
| --- | --- |
| No token | `401`, `WWW-Authenticate: Bearer resource_metadata="https://mcp.acme.com/.well-known/oauth-protected-resource/mcp"` |
| A token that fails: bad signature, expired, another audience or issuer | the same `401` |
| A valid token without a tool's scope | the tool is missing from `tools/list`, and `tools/call` for it is a JSON-RPC error |
| A valid token | the request goes to your server |

agentgateway's challenge has no `scope` or `error="invalid_token"`, unlike
pontkit's middleware. MCP clients need only `resource_metadata`: they read
the metadata, then sign the user in at Pontive.

## Test it [#test-it]

The metadata, and the challenge:

```sh
curl -s https://mcp.acme.com/.well-known/oauth-protected-resource/mcp | jq
curl -si -X POST https://mcp.acme.com/mcp | grep -i www-authenticate
```

A token without a user: a service account with a client grant on the API
(*APIs* → the API → *Clients*), then its `client_credentials` token for the
API:

```sh
TOKEN=$(curl -s https://acme.auth.us.pontive.app/oauth2/token \
  -u "$SVC_ID:$SVC_SECRET" \
  -d grant_type=client_credentials \
  -d resource=https://mcp.acme.com/mcp | jq -r .access_token)

curl -s https://mcp.acme.com/mcp -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'
```

With a user, from Claude Code:

```sh
claude mcp add --transport http acme-files https://mcp.acme.com/mcp
```

Then run `/mcp` in Claude Code and choose *Authenticate*. It reads the
metadata, registers with your instance, opens the sign-in and consent page
(listing the tools the user allows), and connects with the token it gets.

## Limits [#limits]

- **One issuer per route.** `mcpAuthentication` takes one `issuer`. A token's
  `iss` is the auth domain that served it, so with a custom auth domain beside
  the default one, set the domain your clients use: MCP clients use the one
  the metadata names. pontkit's middleware and Envoy (`jwt_authn`, several
  providers) accept a list.
- **`typ` is not checked.** agentgateway does not check that the token is an
  access token (`typ: at+jwt`). A Pontive ID token never carries an API's
  identifier as `aud`, so the audience check refuses it anyway. A server that
  verifies with pontkit's middleware checks `typ` too.
- **Scopes are consent, not permission.** A tool scope says the user let the
  client call the tool. Whether the user may do what the call asks is your
  server's check, on `roles` and `permissions` or Pontive's authorization
  check ([mcp-server.md](/docs/sdk/mcp-server#the-principal)). agentgateway can also
  call an external authorization service per request (`extAuthz`); a Pontive
  decision service for it, which checks permissions and records usage in one
  call, is planned.

## See also [#see-also]

- [Secure an MCP server with Pontive and Envoy](/docs/sdk/mcp-server-envoy)
- [Protect an MCP server with Pontive (TypeScript)](/docs/sdk/mcp-server), the middleware in your server
