envoy-guide
Module 6 · Real-world Recipes·25 min·advanced

Putting it all together — the MCP gateway

Stack JWT auth, ext_authz, rate limiting, and JSON↔gRPC transcoding into one production-grade gateway.

The shape

This is the deployment your architecture targets: HTTP/JSON clients (browsers, partners, CLIs) talking to a gRPC backend (an MCP server) through one Envoy that handles auth · quota · transcoding · observability.

The filter order, and why it matters

Text
1. jwt_authn          → reject unauthenticated requests early; populate claims
2. ext_authz          → fine-grained policy using those claims; deny early
3. local_ratelimit    → per-pod safety net against bursts
4. ratelimit          → global per-tenant quota
5. grpc_json_transcoder → JSON ↔ gRPC translation last
6. router             → terminal — dispatches to the upstream

Cheap filters first, expensive filters last. Putting the transcoder before auth means attackers can force JSON-to-protobuf parsing for requests you'll reject anyway. Token-bucket math is virtually free, so ratelimit comes after auth but before transcoding. The router is always terminal — it's the filter that actually opens the upstream connection.

The complete envoy.yaml

YAML
admin:
  address: { socket_address: { address: 0.0.0.0, port_value: 9901 }}

static_resources:
  listeners:
  - name: mcp_gateway
    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_gw
          codec_type: AUTO
          generate_request_id: true
          tracing:
            provider:
              name: envoy.tracers.opentelemetry
              typed_config:
                "@type": type.googleapis.com/envoy.config.trace.v3.OpenTelemetryConfig
                grpc_service: { envoy_grpc: { cluster_name: otel_collector }}
                service_name: mcp-gateway
          access_log:
          - name: envoy.access_loggers.stdout
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog
              log_format:
                json_format:
                  ts: "%START_TIME%"
                  method: "%REQ(:METHOD)%"
                  path: "%REQ(:PATH)%"
                  status: "%RESPONSE_CODE%"
                  grpc_status: "%GRPC_STATUS%"
                  tenant: "%REQ(x-tenant-id)%"
                  duration_ms: "%DURATION%"
                  trace_id: "%REQ(x-request-id)%"
          route_config:
            virtual_hosts:
            - name: api
              domains: ["*"]
              routes:
              - match: { prefix: "/v1/" }
                route:
                  cluster: mcp_cluster
                  timeout: 60s
                  rate_limits:
                  - actions:
                    - request_headers:
                        header_name: x-tenant-id
                        descriptor_key: tenant
              - match: { prefix: "/healthz" }
                direct_response: { status: 200, body: { inline_string: "ok" }}

          http_filters:
          # 1 — JWT
          - name: envoy.filters.http.jwt_authn
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
              providers:
                idp:
                  issuer: https://auth.example.com/
                  audiences: ["mcp-api"]
                  remote_jwks:
                    http_uri: { uri: https://auth.example.com/.well-known/jwks.json, cluster: idp_jwks, timeout: 5s }
                    cache_duration: { seconds: 600 }
                  payload_in_metadata: jwt_payload
              rules:
              - match: { prefix: "/v1/" }
                requires: { provider_name: idp }

          # 2 — ext_authz (OPA)
          - name: envoy.filters.http.ext_authz
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
              transport_api_version: V3
              grpc_service:
                envoy_grpc: { cluster_name: opa_authz }
                timeout: 0.25s
              failure_mode_allow: false
              metadata_context_namespaces: [envoy.filters.http.jwt_authn]

          # 3 — local rate limit (safety net)
          - name: envoy.filters.http.local_ratelimit
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit
              stat_prefix: gw_local_rl
              token_bucket: { max_tokens: 200, tokens_per_fill: 200, fill_interval: 1s }
              filter_enabled:  { default_value: { numerator: 100, denominator: HUNDRED }}
              filter_enforced: { default_value: { numerator: 100, denominator: HUNDRED }}

          # 4 — global rate limit (per-tenant)
          - name: envoy.filters.http.ratelimit
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.ratelimit.v3.RateLimit
              domain: mcp_api
              transport_api_version: V3
              rate_limit_service:
                transport_api_version: V3
                grpc_service: { envoy_grpc: { cluster_name: ratelimit_cluster }}

          # 5 — JSON ↔ gRPC
          - name: envoy.filters.http.grpc_json_transcoder
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.grpc_json_transcoder.v3.GrpcJsonTranscoder
              proto_descriptor: /etc/envoy/mcp.pb
              services: ["mcp.v1.ToolService", "mcp.v1.SessionService"]
              convert_grpc_status: true
              print_options: { add_whitespace: true, always_print_primitive_fields: true }
              request_validation_options:
                reject_unknown_method: true
                reject_unknown_query_parameters: true

          # 6 — router (terminal)
          - name: envoy.filters.http.router
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router

  clusters:
  - name: mcp_cluster
    type: STRICT_DNS
    connect_timeout: 1s
    typed_extension_protocol_options:
      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
        "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
        explicit_http_config: { http2_protocol_options: {} }
    load_assignment:
      cluster_name: mcp_cluster
      endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: mcp, port_value: 50051 }}}}]}]

  - name: idp_jwks
    type: LOGICAL_DNS
    connect_timeout: 2s
    transport_socket:
      name: envoy.transport_sockets.tls
      typed_config: { "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext }
    load_assignment:
      cluster_name: idp_jwks
      endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: auth.example.com, port_value: 443 }}}}]}]

  - name: opa_authz
    type: STRICT_DNS
    connect_timeout: 0.25s
    typed_extension_protocol_options:
      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
        "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
        explicit_http_config: { http2_protocol_options: {} }
    load_assignment:
      cluster_name: opa_authz
      endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: opa, port_value: 9191 }}}}]}]

  - name: ratelimit_cluster
    type: STRICT_DNS
    connect_timeout: 0.25s
    typed_extension_protocol_options:
      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
        "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
        explicit_http_config: { http2_protocol_options: {} }
    load_assignment:
      cluster_name: ratelimit_cluster
      endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: ratelimit, port_value: 8081 }}}}]}]

  - name: otel_collector
    type: STRICT_DNS
    connect_timeout: 1s
    typed_extension_protocol_options:
      envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
        "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
        explicit_http_config: { http2_protocol_options: {} }
    load_assignment:
      cluster_name: otel_collector
      endpoints: [{ lb_endpoints: [{ endpoint: { address: { socket_address: { address: otel-collector, port_value: 4317 }}}}]}]

That's the whole gateway. ~150 lines for what would otherwise be a multi-thousand-line bespoke service.

Who can deny what

Each filter is its own gate. Failures are clean, observable, and cheap because rejections stop the chain immediately.

Observability tie-in

  • Per-route metrics come for free as envoy_cluster_grpc_* and envoy_cluster_upstream_rq_* tagged by cluster name.
  • Tracing survives transcoding: the traceparent (or x-b3-*) header on the JSON request is preserved into the gRPC call, so your MCP server's spans become children of the Envoy span. One trace, multiple hops, zero glue code.
  • Access logs include %GRPC_STATUS% so you see the protobuf-level outcome — not just "HTTP 200" hiding a grpc-status: 13 INTERNAL.

Hands-on: end-to-end on your laptop

Hands-on · Bring up the whole stack with docker compose

This is the longest hands-on of the course but it's the proof that the whole architecture composes.

  1. Take the envoy.yaml above. Replace auth.example.com with a local Keycloak (Lesson 19) or a mock JWKS server. Replace the MCP cluster with any gRPC service (the bookstore sample from Lesson 18 is fine if you don't have an MCP server handy).

  2. docker compose up the following services:

    • envoy — the gateway above
    • opa — openpolicyagent/opa:latest-envoy with a tiny allow-everything Rego policy to start
    • ratelimit — envoyproxy/ratelimit:latest + a Redis sidecar + a YAML config defining the mcp_api domain
    • otel-collector — otel/opentelemetry-collector:latest
    • your gRPC backend (MCP server or bookstore sample)
  3. Walk each deny path:

Shell
# 1. No JWT
curl -i localhost:8080/v1/tools          # 401

# 2. Get a JWT (Lesson 19 recipe)
TOKEN=$(...)

# 3. JWT but OPA denies (tighten the Rego, then retry)
curl -i -H "Authorization: Bearer $TOKEN" localhost:8080/v1/tools  # 403

# 4. Loosen Rego, hit it 250 times in a second
for i in $(seq 1 250); do
  curl -s -o /dev/null -w "%{http_code}\n" \
    -H "Authorization: Bearer $TOKEN" \
    localhost:8080/v1/tools
done | sort | uniq -c
# expect: ~200 of "200" then 50 of "429"

# 5. Happy path — JSON in, gRPC backend handled it
curl -s -H "Authorization: Bearer $TOKEN" \
  -H "x-tenant-id: acme" \
  localhost:8080/v1/tools/abc | jq

If all five paths produce the right status code, your gateway is real.

What changes for production

A few knobs you'd tune before going live:

  • TLS on the listener (Lesson 9) — terminate HTTPS at the gateway.
  • Active health checks on the OPA and RLS clusters — fail closed if they're down (default).
  • Outlier detection on the MCP cluster — eject misbehaving replicas automatically.
  • Move from static config to xDS (Lesson 16) — push routes/clusters from a control plane instead of restarting Envoy.
  • Rate-limit overrides per-route via typed_per_filter_config for special endpoints.
Real-world example · Your MCP gateway team
Problem
The MCP backend speaks gRPC. Customers (browsers, integrations, CLIs) want REST. Different tiers need different quotas. Some routes need fine-grained policy beyond simple JWT scopes. The team has neither the time nor the desire to write a custom gateway service.
Envoy solution
The 150-line envoy.yaml above. Five composable filters from upstream Envoy do the work of an entire bespoke gateway. New endpoints = annotate one new RPC + regenerate mcp.pb. New tenant tier = one entry in the rate-limit YAML. New policy = one Rego rule. Zero application code touched.

You've finished the real-world module

You now have a production-shaped Envoy deployment in your head. From here, the natural extensions are:

  • WASM filters — write request/response logic in Rust/Go and load it dynamically.
  • ext_proc — bidirectional, message-by-message body mutation (PII redaction, prompt rewriting, content moderation).
  • Envoy Gateway / Kubernetes Gateway API — the upstream "easy mode" for running this whole stack on K8s with declarative CRDs.
  • Dynamic forward proxy — egress with on-demand DNS resolution.
  • SDS — push TLS certs into Envoy without restart.

Each of those is a future lesson. You now have the foundation to read their docs without flinching.

Quick check

In the full filter chain, where does grpc_json_transcoder belong relative to jwt_authn, ext_authz, and ratelimit?

Practical task
Finish the quick check and tick off the task to unlock.
Quick checkTasks 0/4