# Secure an MCP server with Pontive and Envoy

> Check Pontive access tokens for an MCP server at an Envoy proxy, with jwt_authn and RBAC.

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

For an MCP server behind [Envoy](https://www.envoyproxy.io). Envoy's
`jwt_authn` filter checks every request's Pontive access token against your
instance's keys before it reaches your server, an RBAC rule requires a scope,
and Envoy itself serves the server's protected resource metadata (RFC 9728)
and the `401` challenge that points MCP clients at it. MCP clients such as
Claude Code then sign the user in at your Pontive instance on their own.

```
MCP client ──► Envoy (jwt_authn, RBAC) ──► your MCP server
   │  401 + resource_metadata
   └──► Pontive (sign-in, consent, token for the API)
```

Envoy needs nothing Pontive-specific: Pontive is a standard OAuth 2.1
authorization server, and the token is a signed JWT. Tested with Envoy
v1.40.2. The configuration below runs in Pontive's conformance suite against a
live instance on every run.

## 1. Register the MCP server as an API, and find your issuer [#1-register-the-mcp-server-as-an-api-and-find-your-issuer]

As in the [agentgateway guide](/docs/sdk/mcp-server-agentgateway#1-register-the-mcp-server-as-an-api):
the API's identifier is the server's **public MCP URL**
(`https://mcp.acme.com/mcp`), mark it `third_party` and add it to the
third-party client profile so MCP clients can connect, and give it its scopes.
This guide's RBAC rule requires `files:read`.

Your issuer is your auth domain, e.g. `https://acme.auth.us.pontive.app`, and
its keys are at its discovery document's `jwks_uri`:
`https://acme.auth.us.pontive.app/oauth2/jwks.json`.

## 2. Configure Envoy [#2-configure-envoy]

```yaml
# envoy.yaml
static_resources:
  listeners:
  - name: mcp
    address:
      socket_address: { address: 0.0.0.0, port_value: 8080 }
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: mcp
          route_config:
            virtual_hosts:
            - name: mcp
              domains: ["*"]
              routes:
              # The protected resource metadata, at the identifier's well-known
              # path and the bare one. MCP clients read it after the 401.
              - match: { path: /.well-known/oauth-protected-resource/mcp }
                direct_response: &metadata
                  status: 200
                  body:
                    inline_string: '{"resource":"https://mcp.acme.com/mcp","authorization_servers":["https://acme.auth.us.pontive.app"],"scopes_supported":["files:read","files:write"],"bearer_methods_supported":["header"],"resource_name":"Acme Files"}'
                response_headers_to_add: &metadata_headers
                - header: { key: content-type, value: application/json }
                - header: { key: cache-control, value: max-age=300 }
                - header: { key: access-control-allow-origin, value: "*" }
              - match: { path: /.well-known/oauth-protected-resource }
                direct_response: *metadata
                response_headers_to_add: *metadata_headers
              - match: { path: /mcp }
                route: { cluster: mcp_server, timeout: 60s }
          # Envoy's own 401 and 403 carry the challenges an MCP client acts on.
          local_reply_config:
            mappers:
            # jwt_authn answers 403 for a token for another audience; it is an
            # invalid token for this API (RFC 6750 §3.1), so 401.
            - filter:
                extension_filter:
                  name: envoy.access_loggers.extension_filters.cel
                  typed_config:
                    "@type": type.googleapis.com/envoy.extensions.access_loggers.filters.cel.v3.ExpressionFilter
                    expression: response.code == 403 && response.code_details.startsWith("jwt_authn_access_denied")
              status_code: 401
              headers_to_add:
              - header: { key: www-authenticate, value: 'Bearer resource_metadata="https://mcp.acme.com/.well-known/oauth-protected-resource/mcp", scope="files:read", error="invalid_token"' }
                append_action: OVERWRITE_IF_EXISTS_OR_ADD
            - filter:
                and_filter:
                  filters:
                  - status_code_filter: { comparison: { op: EQ, value: { default_value: 401, runtime_key: unused_401 } } }
                  - header_filter: { header: { name: authorization, present_match: true } }
              headers_to_add:
              - header: { key: www-authenticate, value: 'Bearer resource_metadata="https://mcp.acme.com/.well-known/oauth-protected-resource/mcp", scope="files:read", error="invalid_token"' }
                append_action: OVERWRITE_IF_EXISTS_OR_ADD
            - filter:
                status_code_filter: { comparison: { op: EQ, value: { default_value: 401, runtime_key: unused_401b } } }
              headers_to_add:
              - header: { key: www-authenticate, value: 'Bearer resource_metadata="https://mcp.acme.com/.well-known/oauth-protected-resource/mcp", scope="files:read"' }
                append_action: OVERWRITE_IF_EXISTS_OR_ADD
            - filter:
                status_code_filter: { comparison: { op: EQ, value: { default_value: 403, runtime_key: unused_403 } } }
              headers_to_add:
              - header: { key: www-authenticate, value: 'Bearer error="insufficient_scope", scope="files:read", resource_metadata="https://mcp.acme.com/.well-known/oauth-protected-resource/mcp"' }
                append_action: OVERWRITE_IF_EXISTS_OR_ADD
          http_filters:
          - name: envoy.filters.http.jwt_authn
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
              providers:
                pontive:
                  issuer: https://acme.auth.us.pontive.app
                  audiences: ["https://mcp.acme.com/mcp"]       # the API's identifier
                  remote_jwks:
                    http_uri:
                      uri: https://acme.auth.us.pontive.app/oauth2/jwks.json
                      cluster: pontive_jwks
                      timeout: 5s
                    cache_duration: 300s
                    async_fetch: {}
                    retry_policy: {}
                  forward: true                  # your server receives the token too
                  payload_in_metadata: jwt_payload
                  clock_skew_seconds: 60
              rules:
              - match: { prefix: /.well-known/ }  # the metadata: no token
              - match: { prefix: / }
                requires: { provider_name: pontive }
          # The token must carry files:read. Pontive's scope claim is one
          # space-separated string.
          - name: envoy.filters.http.rbac
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC
              rules:
                action: ALLOW
                policies:
                  metadata:
                    permissions: [{ url_path: { path: { prefix: /.well-known/ } } }]
                    principals: [{ any: true }]
                  scope:
                    permissions: [{ any: true }]
                    principals:
                    - sourced_metadata:
                        metadata_source: DYNAMIC
                        metadata_matcher:
                          filter: envoy.filters.http.jwt_authn
                          path: [{ key: jwt_payload }, { key: scope }]
                          value: { string_match: { safe_regex: { regex: "(.* )?files:read( .*)?" } } }
          - name: envoy.filters.http.router
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
  clusters:
  - name: mcp_server                       # your MCP server
    type: STRICT_DNS
    load_assignment:
      cluster_name: mcp_server
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address: { address: files-mcp.internal, port_value: 8080 }
  - name: pontive_jwks                     # your auth domain, for the keys
    type: LOGICAL_DNS
    dns_lookup_family: V4_ONLY
    load_assignment:
      cluster_name: pontive_jwks
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address: { address: acme.auth.us.pontive.app, port_value: 443 }
    transport_socket:
      name: envoy.transport_sockets.tls
      typed_config:
        "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
        sni: acme.auth.us.pontive.app
        common_tls_context:
          validation_context:
            trusted_ca: { filename: /etc/ssl/certs/ca-certificates.crt }
            match_typed_subject_alt_names:
            - san_type: DNS
              matcher: { exact: acme.auth.us.pontive.app }
```

| Part | Why |
| --- | --- |
| `direct_response` routes | Envoy serves the metadata itself. `resource` is the identifier, `authorization_servers` your issuer, `scopes_supported` the API's scopes. Keep them equal to the API's, or fetch the document from `GET /v1/apis/{api_id}/resource-metadata` when you deploy. |
| `jwt_authn` provider | `issuer` is compared with `iss`, `audiences` with `aud`: a token for another API, or with no `resource` (its `aud` is the client's own id), is refused. `remote_jwks` fetches Pontive's keys through the `pontive_jwks` cluster, over TLS, and caches them. |
| `rules` | The metadata paths need no token; everything else needs a Pontive token. |
| `forward: true` | Your server receives the token too, to verify it again (for example with `@pontive/pontkit-server`'s middleware, [mcp-server.md](/docs/sdk/mcp-server), with the same identifier) or to read the caller. Its audience is this API, so this is not token passthrough to another API. |
| RBAC | Requires a scope. Envoy sees HTTP, not MCP: it cannot tell one tool from another (below). |
| `local_reply_config` | Envoy's own `401` and `403` get the `WWW-Authenticate` headers pontkit's middleware sends: `resource_metadata` and `scope`, `error="invalid_token"` when a token was sent, and `insufficient_scope` on RBAC's `403`. `jwt_authn` answers a token for another audience with `403`; the first mapper makes it the `401 invalid_token` RFC 6750 asks for, so the client signs in again instead of giving up. Only Envoy's own replies are rewritten, never your server's. |

**Several auth domains.** A token's `iss` is the auth domain that served it.
With a custom auth domain beside the default one, add a provider per domain
(each with its `remote_jwks` and cluster) and require either:
`requires: { requires_any: { requirements: [{ provider_name: pontive }, { provider_name: pontive_custom }] } }`.
List both in the metadata's `authorization_servers`.

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

```sh
docker run --rm -p 8080:8080 -v "$PWD/envoy.yaml:/etc/envoy/envoy.yaml:ro" \
  envoyproxy/envoy:v1.40.2 -c /etc/envoy/envoy.yaml
```

In front of it, your TLS terminator serves `https://mcp.acme.com`, the
origin of the identifier.

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

| Request | Answer from Envoy |
| --- | --- |
| No token | `401`, `WWW-Authenticate: Bearer resource_metadata="…/.well-known/oauth-protected-resource/mcp", scope="files:read"` |
| A token that fails: bad signature, expired, another audience or issuer | the same, plus `error="invalid_token"` |
| A valid token without `files:read` | `403`, `WWW-Authenticate: Bearer error="insufficient_scope", scope="files:read", resource_metadata="…"` |
| A valid token | the request goes to your server, with the token |

## Test it [#test-it]

```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 service account with a client grant on the API gets a token without a user:

```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 `/mcp` in Claude Code, *Authenticate*: it reads the metadata, registers
with your instance, opens the sign-in and consent page, and connects.

## Per tool, and per permission [#per-tool-and-per-permission]

Envoy authorizes the HTTP request, so the RBAC rule applies to every MCP
method alike. For one scope per tool (`tool:<name>`, from Pontive's tool
import), check the tool in your server: pontkit's middleware maps a tool call
to its scope ([mcp-server.md](/docs/sdk/mcp-server)). agentgateway parses MCP and
checks tool scopes at the gateway
([agentgateway guide](/docs/sdk/mcp-server-agentgateway)).

Scopes are consent, not permission: whether the user may do what a call asks
is your server's check, on the token's `roles` and `permissions` or Pontive's
authorization check. A Pontive external authorization service for Envoy's
`ext_authz` filter is planned: a container you run beside Envoy that maps
routes and MCP tools to permissions and answers each call with one
authorization and billing decision. Until then, `jwt_authn` and RBAC as above
are the gateway's part.

## See also [#see-also]

- [Secure an MCP server with Pontive and agentgateway](/docs/sdk/mcp-server-agentgateway)
- [Protect an MCP server with Pontive (TypeScript)](/docs/sdk/mcp-server)
