Skip to content

Decide each tool call behind Gravitee

Put an MCP server behind Gravitee API Management Community Edition with Keycard sign-in, and let Keycard policy allow or refuse each tool call.

Gravitee API Management can sit in front of an MCP server as the place access is enforced, with Keycard deciding each tool call. Gravitee asks Keycard about every MCP request with policies that ship in its Community Edition, with no license, and forwards the request only if Keycard policy allows that tool, so you can take one tool away while the others keep working.

  1. MCP client Signs the person in through Keycard and calls a tool through Gravitee with a token for Gravitee’s endpoint.
  2. Gravitee Checks the token in its JWT plan, then exchanges it with Keycard and names the tool in the request.
  3. Keycard Decides through policy whether that person may call that tool, and issues a token for the MCP server or refuses with a reason.
  4. Orders MCP server Receives the call with the new token, or never sees it, while Gravitee answers 403 with Keycard’s reason.
  • The Kong recipe’s repository, keycardai/tutorial-kong-mcp, cloned. This recipe uses its orders MCP server and its Keycard setup scripts. Run the commands on this page from its root unless a step says otherwise.
  • A Keycard organization where you have the Admin Role. Your issuer URL is under Settings → Connection in Keycard Console, and has the form https://<zone-id>.keycard.cloud. The steps set it as KEYCARD_ISSUER.
  • A Service Account credential for the Management API: in Keycard Console, go to Organization → Service Accounts → Create service account → Add credential.
  • Docker with Docker Compose, Python 3.12 or later, uv, curl, and jq.
  • An MCP client. This recipe uses Claude Code.

This recipe was tested with Gravitee API Management 4.13.3 Community Edition with no license, FastMCP 4.1.6, and Claude Code 2.1.321.

This recipe assumes your organization runs the managed default-zone-policies Policy Set, which allows every tool. If you run a Policy Set of your own, make sure it lets you call the orders server’s tools through Gravitee. See Access Policies.

This Compose file is Gravitee’s MongoDB quick setup with the version pinned to 4.13.3 and without the developer portal. With no license file, Gravitee runs Community Edition.

  1. Save the Compose file

    From the repository root, create the folder Gravitee mounts for a license, and leave it empty:

    Terminal window
    mkdir -p gravitee/license

    Save this as gravitee/docker-compose.yml:

    networks:
    gio_front: {}
    gio_storage: {}
    volumes:
    data-elasticsearch: {}
    data-mongo: {}
    services:
    mongodb:
    image: mongo:6.0
    restart: "no"
    volumes: [data-mongo:/data/db]
    healthcheck:
    test: mongosh --eval 'db.runCommand({serverStatus:1}).ok' --quiet | grep 1
    interval: 5s
    timeout: 3s
    retries: 20
    networks: [gio_storage]
    elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:8.17.2
    restart: "no"
    volumes: [data-elasticsearch:/usr/share/elasticsearch/data]
    environment:
    - http.host=0.0.0.0
    - transport.host=0.0.0.0
    - xpack.security.enabled=false
    - cluster.name=elasticsearch
    - discovery.type=single-node
    - 'ES_JAVA_OPTS=-Xms512m -Xmx512m'
    healthcheck:
    test: ['CMD', 'curl', '-f', 'http://localhost:9200/_cluster/health?wait_for_status=yellow&timeout=5s']
    interval: 5s
    timeout: 3s
    retries: 30
    networks: [gio_storage]
    gateway:
    image: graviteeio/apim-gateway:4.13.3
    restart: "no"
    ports: ['8082:8082']
    extra_hosts: ['host.docker.internal:host-gateway']
    depends_on:
    mongodb: {condition: service_healthy}
    elasticsearch: {condition: service_healthy}
    volumes:
    - ./license:/opt/graviteeio-gateway/license
    environment:
    - gravitee_management_mongodb_uri=mongodb://mongodb:27017/gravitee?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000&socketTimeoutMS=5000
    - gravitee_ratelimit_mongodb_uri=mongodb://mongodb:27017/gravitee?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000&socketTimeoutMS=5000
    - gravitee_reporters_elasticsearch_endpoints_0=http://elasticsearch:9200
    networks: [gio_storage, gio_front]
    management_api:
    image: graviteeio/apim-management-api:4.13.3
    restart: "no"
    ports: ['8083:8083']
    depends_on:
    mongodb: {condition: service_healthy}
    elasticsearch: {condition: service_healthy}
    volumes:
    - ./license:/opt/graviteeio-management-api/license
    environment:
    - gravitee_management_mongodb_uri=mongodb://mongodb:27017/gravitee?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000&socketTimeoutMS=5000
    - gravitee_analytics_elasticsearch_endpoints_0=http://elasticsearch:9200
    networks: [gio_storage, gio_front]
    management_ui:
    image: graviteeio/apim-management-ui:4.13.3
    restart: "no"
    ports: ['8084:8080']
    depends_on: [management_api]
    environment:
    - MGMT_API_URL=http://localhost:8083/management/
    networks: [gio_front]
  2. Start Gravitee

    Terminal window
    docker compose -f gravitee/docker-compose.yml up -d

    Gravitee’s gateway listens on port 8082 and its Management API on port 8083. With extra_hosts, the gateway can reach the orders server on your machine at host.docker.internal.

Two scripts from the Kong recipe register Gravitee and the orders server in Keycard through the Management API, with your Service Account credential.

  1. Run the setup scripts

    Terminal window
    export KEYCARD_CLIENT_ID=<service-account-client-id>
    export KEYCARD_CLIENT_SECRET=<service-account-client-secret>
    export KEYCARD_ISSUER=https://<zone-id>.keycard.cloud
    export MCP_RESOURCE=http://localhost:8082/orders/mcp
    export ORDERS_RESOURCE=http://localhost:8091/mcp
    export KONG_APP_IDENTIFIER=gravitee-gateway
    export KONG_CREDENTIAL_FILE=./gravitee-gateway.env
    ./keycard/setup.sh
    ./keycard/setup-exchange.sh

    setup.sh registers Gravitee’s endpoint, http://localhost:8082/orders/mcp, as a Resource with the scope mcp:tools. setup-exchange.sh creates the Application gravitee-gateway that Gravitee authenticates as when it exchanges tokens, saves its client ID and secret to gravitee-gateway.env (git ignores it), and makes it the provider of Gravitee’s endpoint. It also registers the orders server as the Resource http://localhost:8091/mcp, a dependency of that Application when it accesses Gravitee’s endpoint.

    The scripts come from the Kong recipe, so the Application they create is named Kong AI Gateway and the endpoint Resource Orders MCP (through Kong). You don’t need the export lines they print, because the next steps use the variables you set here.

  1. Run the orders server

    In a new terminal, from the repository root:

    Terminal window
    export KEYCARD_ISSUER=https://<zone-id>.keycard.cloud
    export GATEWAY_CLIENT_ID=$(sed -n 's/^KONG_KEYCARD_CLIENT_ID=//p' gravitee-gateway.env)
    export ORDERS_RESOURCE=http://localhost:8091/mcp PORT=8091
    cd orders-mcp
    uv run orders-mcp

    It listens on http://localhost:8091/mcp and accepts a token only if Keycard issued it for this server to Gravitee’s Application. Leave it running.

These steps create a v4 proxy API at /orders/mcp through Gravitee’s Management API, with Gravitee’s default admin login. Gravitee signs callers in with Keycard through the API’s JWT plan, and asks Keycard about every request in the API’s request flow. How the Gravitee config fits together explains each part.

  1. Set the Management API URLs and Gravitee’s Keycard credential

    Back in the first terminal, where KEYCARD_ISSUER is still set:

    Terminal window
    export GRAVITEE_MGMT=http://localhost:8083/management/v2/environments/DEFAULT
    export GRAVITEE_ORG=http://localhost:8083/management/organizations/DEFAULT/environments/DEFAULT
    set -a; . ./gravitee-gateway.env; set +a
    export KEYCARD_BASIC="Basic $(printf '%s:%s' "$KONG_KEYCARD_CLIENT_ID" "$KONG_KEYCARD_CLIENT_SECRET" | base64 | tr -d '\n')"
  2. Save the Groovy script

    Save this as gravitee/exchange.groovy. Gravitee runs it on every request to build the token exchange request for Keycard.

    import groovy.json.JsonSlurper
    import groovy.json.JsonOutput
    import io.gravitee.policy.groovy.PolicyResult.State
    def server = context.getAttribute('kc.server')
    def body = request.content
    def msg = null
    if (body != null && body.trim()) {
    try { msg = new JsonSlurper().parseText(body) } catch (Exception e) { msg = 'UNPARSEABLE' }
    }
    def detail = null
    def bad = null
    if (msg instanceof List) {
    bad = 'Send one JSON-RPC message per request'
    } else if (msg instanceof Map && msg.method instanceof String) {
    def m = msg.method
    if (m == 'tools/call') {
    def n = (msg.params instanceof Map) ? msg.params.name : null
    if (n instanceof String && n ==~ /^[A-Za-z0-9_.-]+$/) {
    detail = [type: 'mcp', action: 'tools/call', name: n, locations: [server]]
    } else {
    bad = 'tools/call needs a valid tool name'
    }
    } else if (m in ['tools/list', 'prompts/list', 'resources/list', 'resources/templates/list']) {
    detail = [type: 'mcp', action: m, locations: [server]]
    }
    } else if (msg == 'UNPARSEABLE') {
    bad = 'Request body is not JSON'
    }
    if (bad != null) {
    result.key = 'KEYCARD_BAD_REQUEST'
    result.state = State.FAILURE
    result.code = 400
    result.contentType = 'application/json'
    result.error = JsonOutput.toJson([error: 'invalid_request', error_description: bad])
    return
    }
    if (detail == null) {
    detail = [type: 'mcp', action: 'initialize', locations: [server]]
    }
    def h = request.headers.get('Authorization')
    def authz = (h instanceof List) ? (h ? (h[0] as String) : '') : ((h ?: '') as String)
    def subject = authz.replaceFirst(/(?i)^bearer\s+/, '')
    def enc = { s -> java.net.URLEncoder.encode(s as String, 'UTF-8') }
    def form = [
    grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
    subject_token: subject,
    subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',
    resource: server,
    authorization_details: JsonOutput.toJson([detail])
    ].collect { k, v -> enc(k) + '=' + enc(v) }.join('&')
    context.setAttribute('kc.form', form)
    context.setAttribute('kc.action', detail.action + (detail.name ? ':' + detail.name : ''))
  3. Save the API definition

    Save this as gravitee/orders-api.json. The script, the token endpoint URL, and the Authorization value are empty here, and the next step fills them in.

    {
    "name": "orders-mcp",
    "apiVersion": "1.0",
    "definitionVersion": "V4",
    "type": "PROXY",
    "listeners": [
    {
    "type": "HTTP",
    "paths": [{ "path": "/orders/mcp" }],
    "entrypoints": [{ "type": "http-proxy" }]
    }
    ],
    "endpointGroups": [
    {
    "name": "default",
    "type": "http-proxy",
    "endpoints": [
    {
    "name": "orders",
    "type": "http-proxy",
    "weight": 1,
    "inheritConfiguration": false,
    "configuration": { "target": "http://host.docker.internal:8091/mcp" }
    }
    ]
    }
    ],
    "flowExecution": { "mode": "DEFAULT", "matchRequired": false },
    "flows": [
    {
    "name": "keycard-exchange",
    "enabled": true,
    "selectors": [{ "type": "HTTP", "path": "/", "pathOperator": "STARTS_WITH", "methods": [] }],
    "request": [
    {
    "name": "Set server",
    "policy": "policy-assign-attributes",
    "enabled": true,
    "configuration": {
    "attributes": [{ "name": "kc.server", "value": "http://localhost:8091/mcp" }]
    }
    },
    {
    "name": "Build exchange form",
    "policy": "groovy",
    "enabled": true,
    "configuration": { "readContent": true, "overrideContent": false, "script": "" }
    },
    {
    "name": "Token exchange",
    "policy": "policy-http-callout",
    "enabled": true,
    "configuration": {
    "method": "POST",
    "url": "",
    "headers": [
    { "name": "Content-Type", "value": "application/x-www-form-urlencoded" },
    { "name": "Authorization", "value": "" }
    ],
    "body": "{#context.attributes['kc.form']}",
    "variables": [
    { "name": "kc.token", "value": "{#jsonPath(#calloutResponse.content, '$.access_token')}" }
    ],
    "exitOnError": true,
    "errorCondition": "{#calloutResponse.status >= 400}",
    "errorStatusCode": "403",
    "errorContent": "{\"error\":\"access_denied\",\"error_description\":\"Keycard refused this call: {#jsonPath(#calloutResponse.content, '$.error_description').replace('\"', '''')}\"}"
    }
    },
    {
    "name": "Swap in the issued token",
    "policy": "transform-headers",
    "enabled": true,
    "configuration": {
    "addHeaders": [
    { "name": "Authorization", "value": "Bearer {#context.attributes['kc.token']}" }
    ]
    }
    }
    ],
    "response": []
    }
    ]
    }
  4. Create the API

    Terminal window
    API_ID=$(jq --rawfile script gravitee/exchange.groovy \
    '.flows[0].request[1].configuration.script = $script
    | .flows[0].request[2].configuration.url = env.KEYCARD_ISSUER + "/oauth/2/token"
    | .flows[0].request[2].configuration.headers[1].value = env.KEYCARD_BASIC' \
    gravitee/orders-api.json |
    curl -sS --fail-with-body -u admin:admin -H 'Content-Type: application/json' -d @- "$GRAVITEE_MGMT/apis" |
    jq -r .id)
  5. Add the JWT plan

    Terminal window
    PLAN_ID=$(jq -n '{
    name: "keycard-jwt", definitionVersion: "V4", mode: "STANDARD", validation: "AUTO",
    security: {type: "JWT", configuration: {
    signature: "RSA_RS256",
    publicKeyResolver: "JWKS_URL",
    resolverParameter: (env.KEYCARD_ISSUER + "/openidconnect/jwks"),
    extractClaims: true,
    propagateAuthHeader: true,
    userClaim: "sub",
    protectedResourceMetadata: {authorizationServers: [env.KEYCARD_ISSUER]},
    requiredScopes: ["mcp:tools"],
    checkRequiredScopes: false
    }},
    flows: []
    }' |
    curl -sS --fail-with-body -u admin:admin -H 'Content-Type: application/json' -d @- "$GRAVITEE_MGMT/apis/$API_ID/plans" |
    jq -r .id)
    curl -sS --fail-with-body -u admin:admin -X POST "$GRAVITEE_MGMT/apis/$API_ID/plans/$PLAN_ID/_publish" > /dev/null
  6. Subscribe one application for every Keycard token

    The application’s client ID is Gravitee’s endpoint URL, which every Keycard token for this endpoint carries as aud.

    Terminal window
    APP_ID=$(curl -sS --fail-with-body -u admin:admin -H 'Content-Type: application/json' "$GRAVITEE_ORG/applications" \
    -d '{"name":"keycard-callers","description":"Every Keycard token for the orders endpoint, matched on aud","settings":{"app":{"type":"simple","client_id":"http://localhost:8082/orders/mcp"}}}' |
    jq -r .id)
    jq -n --arg app "$APP_ID" --arg plan "$PLAN_ID" '{applicationId: $app, planId: $plan}' |
    curl -sS --fail-with-body -u admin:admin -H 'Content-Type: application/json' -d @- "$GRAVITEE_MGMT/apis/$API_ID/subscriptions" > /dev/null
  7. Set the response templates

    Gravitee ignores response templates when it creates an API, so this step reads the API back and updates it with them.

    Terminal window
    curl -sS --fail-with-body -u admin:admin "$GRAVITEE_MGMT/apis/$API_ID" |
    jq 'with_entries(select(.key | IN("name", "apiVersion", "definitionVersion", "type", "description",
    "listeners", "endpointGroups", "flows", "flowExecution", "analytics", "properties", "resources",
    "tags", "labels", "visibility", "groups", "categories", "lifecycleState", "failover", "services")))
    | .responseTemplates = {
    CALLOUT_EXIT_ON_ERROR: {"*/*": {statusCode: 403, headers: {"Content-Type": "application/json"}, body: "{#error.message}"}},
    KEYCARD_BAD_REQUEST: {"*/*": {statusCode: 400, headers: {"Content-Type": "application/json"}, body: "{#error.message}"}}
    }' |
    curl -sS --fail-with-body -u admin:admin -X PUT -H 'Content-Type: application/json' -d @- "$GRAVITEE_MGMT/apis/$API_ID" > /dev/null
  8. Start and deploy the API

    Terminal window
    curl -sS --fail-with-body -u admin:admin -X POST "$GRAVITEE_MGMT/apis/$API_ID/_start" > /dev/null
    curl -sS --fail-with-body -u admin:admin -H 'Content-Type: application/json' -d '{"deploymentLabel":"keycard"}' \
    "$GRAVITEE_MGMT/apis/$API_ID/deployments" > /dev/null

    Gravitee now serves the API at http://localhost:8082/orders/mcp.

  1. Send a request without a token

    Terminal window
    curl -i -X POST http://localhost:8082/orders/mcp \
    -H 'content-type: application/json' \
    -d '{"jsonrpc":"2.0","id":0,"method":"initialize"}'

    Gravitee answers 401, and the resource_metadata in its WWW-Authenticate header is http://localhost:8082/orders/mcp/.well-known/oauth-protected-resource.

  2. Read the metadata

    Terminal window
    curl -s http://localhost:8082/orders/mcp/.well-known/oauth-protected-resource

    The metadata names your Keycard issuer:

    {"resource":"http://localhost:8082/orders/mcp","authorization_servers":["https://<zone-id>.keycard.cloud"],"scopes_supported":["mcp:tools"]}
  1. Add the server to Claude Code

    Terminal window
    claude mcp add --transport http gravitee-orders http://localhost:8082/orders/mcp
    claude
  2. Sign in

    Run /mcp, select gravitee-orders, then Authenticate. Claude Code reads Gravitee’s metadata, registers with Keycard, and opens Keycard’s sign-in page. Sign in.

  3. Check the result

    Claude Code connects and lists the orders server’s two tools, list_orders and refund_order. The MCP server’s terminal shows accepted a token for sub=<user-id> from the gateway for each request Gravitee forwarded.

    Keycard’s Audit Log records your sign-in and a credentials:issue with the authorization_code grant, issued to you through the client Claude Code registered. After that comes one credentials:issue with the token exchange grant for each MCP request, issued to you through Gravitee’s Application. Each of those records carries the authorization_details Gravitee sent.

Take one tool away and check that Gravitee refuses it while the other keeps working. keycard/block-refunds.sh copies Keycard’s default policies as the Policy Set gravitee-tutorial, adds a policy that forbids refund_order, and activates the copy.

  1. Run the script

    In the first terminal, where ORDERS_RESOURCE is still set:

    Terminal window
    export POLICY_SET_NAME=gravitee-tutorial
    ./keycard/block-refunds.sh

    It ends with Activated gravitee-tutorial with orders-no-refunds.

  2. List the orders

    Ask Claude to list the orders. Keycard allows list_orders, so Claude lists three orders: A-1001 and A-1003 are shipped, and A-1002 is pending.

  3. Ask for a refund

    Ask Claude to refund order A-1002. Gravitee answers 403, and Claude Code reports Keycard’s reason:

    Error POSTing to endpoint: {"error":"access_denied","error_description":"Keycard refused this call: Action 'mcp::tools/call::refund_order' on 'Orders MCP server' is denied by Policy 'orders-no-refunds' in version 2 of Policy Set 'gravitee-tutorial'."}

    The version number can differ.

  4. Check the order

    Ask Claude to list the pending orders: A-1002 is still pending, because the refund never reached the MCP server. The Audit Log shows that exchange as a credentials:issue failure with the same reason.

To give refunds back, activate default-zone-policies again in Console.

Sign-in, in the keycard-jwt plan:

  • Setting publicKeyResolver to JWKS_URL with resolverParameter set to <keycard-issuer-url>/openidconnect/jwks makes Gravitee check each token’s RS256 signature against the keys Keycard publishes.
  • With protectedResourceMetadata, Gravitee serves protected resource metadata that names your Keycard issuer, and points to it from the 401 it sends a request without a valid token.
  • Gravitee advertises requiredScopes as scopes_supported in that metadata. Setting checkRequiredScopes: false makes Gravitee skip the scope check, because Keycard’s access tokens carry no scope claim.
  • Gravitee admits a token to a JWT plan only when the token’s client ID matches an application subscribed to the plan, and it looks for that client ID in azp, then aud, then client_id. Keycard’s tokens have no azp, so Gravitee matches on aud, which is Gravitee’s endpoint URL, and admits every caller through the one keycard-callers application.

The exchange, in the keycard-exchange flow, which Gravitee runs on every request:

  • In the Set server step, Gravitee sets kc.server to the orders server’s Resource identifier, http://localhost:8091/mcp, which it names in the exchange. Change it there if yours is different. The endpoint’s target is where Gravitee sends the request.
  • In the Groovy policy, Gravitee reads the JSON-RPC message and builds the token exchange request with one authorization_details entry: the tool for tools/call, the method for tools/list, prompts/list, resources/list, and resources/templates/list, and initialize for everything else. A policy can decide each tool call and each of those list methods.
  • In the HTTP Callout policy, Gravitee posts that request to Keycard’s token endpoint with its own client ID and secret as Basic auth. Only the Application that provides a Resource can exchange tokens issued for it, so setup-exchange.sh makes Gravitee’s Application the provider of Gravitee’s endpoint.
  • When Keycard answers with an error, setting exitOnError makes Gravitee stop the request and answer 403 with errorContent: Keycard’s error_description after Keycard refused this call:, with its double quotes replaced by single quotes. The CALLOUT_EXIT_ON_ERROR response template makes Gravitee send that body as it is, instead of wrapping it in its own {"message": ..., "http_status_code": ...} envelope.
  • In the Transform Headers policy, Gravitee replaces the caller’s Authorization header with the token Keycard issued, so the caller’s token never reaches the orders server.

Every policy in this flow ships in Community Edition. Gravitee’s own OAuth2 token exchange policy is an Enterprise feature and can’t send authorization_details, so this recipe uses HTTP Callout instead.

Terminal window
docker compose -f gravitee/docker-compose.yml stop
rm gravitee-gateway.env

Stop the orders server with Ctrl+C. In Keycard Console, activate default-zone-policies again. This recipe also created the gravitee-tutorial Policy Set, the Application Console shows as Kong AI Gateway (identifier gravitee-gateway), and two Resources in Keycard; remove them if you no longer need them.

  • The format Gravitee uses to name the tool in its exchange request, an RFC 9396 authorization detail, is provisional and may change.
  • Gravitee asks Keycard on every request, so each call is its own decision and adds a round trip to Keycard.
  • The token Keycard issues for the MCP server doesn’t say which tool it was issued for. The MCP server has to accept only tokens Keycard issued to Gravitee’s Application, so nothing reaches it without Gravitee’s per-call decision.
  • Gravitee admits a token to a JWT plan only through a subscribed application, so this recipe keys one application to the endpoint URL, and Gravitee admits every caller who signs in with Keycard through it.
  • Gravitee’s client secret is in the HTTP Callout’s Authorization header, in plain text in the API definition, so anyone who can read this API in Gravitee can read it. With its Generate JWT policy, Gravitee can sign a client assertion instead, so Keycard holds only Gravitee’s public key, but this recipe doesn’t cover that setup.
  • If refunds still work after you ran block-refunds.sh again, the script stopped because the orders-no-refunds policy already exists. Activate the gravitee-tutorial Policy Set in Console instead.
  • If a refusal reaches Claude Code wrapped in {"message": ..., "http_status_code": 403}, the API has no CALLOUT_EXIT_ON_ERROR response template. Run step 7 of Create the API in Gravitee again, then the deployments command from step 8.
  • If a batch request, or a tools/call without a valid tool name, gets 403 with Missing required 'grant_type' parameter. as Keycard’s reason, Gravitee carried on after it marked the request failed in the Groovy policy, and sent Keycard an empty exchange request. The call is refused either way. Send one JSON-RPC message per request, and name the tool in each tools/call.
  • If the orders server logs refused a token issued to client <client-id>, not the gateway, GATEWAY_CLIENT_ID isn’t the client ID in gravitee-gateway.env. Set it again and restart the server.

Did this recipe work for you?