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.
- MCP client Signs the person in through Keycard and calls a tool through Gravitee with a token for Gravitee’s endpoint.
- Gravitee Checks the token in its JWT plan, then exchanges it with Keycard and names the tool in the request.
- Keycard Decides through policy whether that person may call that tool, and issues a token for the MCP server or refuses with a reason.
- Orders MCP server Receives the call with the new token, or never sees it, while Gravitee answers
403with Keycard’s reason.
Prerequisites
Section titled “Prerequisites”- 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 asKEYCARD_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, andjq. - 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.
Start Gravitee
Section titled “Start Gravitee”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.
-
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/licenseSave this as
gravitee/docker-compose.yml:networks:gio_front: {}gio_storage: {}volumes:data-elasticsearch: {}data-mongo: {}services:mongodb:image: mongo:6.0restart: "no"volumes: [data-mongo:/data/db]healthcheck:test: mongosh --eval 'db.runCommand({serverStatus:1}).ok' --quiet | grep 1interval: 5stimeout: 3sretries: 20networks: [gio_storage]elasticsearch:image: docker.elastic.co/elasticsearch/elasticsearch:8.17.2restart: "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: 5stimeout: 3sretries: 30networks: [gio_storage]gateway:image: graviteeio/apim-gateway:4.13.3restart: "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/licenseenvironment:- 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:9200networks: [gio_storage, gio_front]management_api:image: graviteeio/apim-management-api:4.13.3restart: "no"ports: ['8083:8083']depends_on:mongodb: {condition: service_healthy}elasticsearch: {condition: service_healthy}volumes:- ./license:/opt/graviteeio-management-api/licenseenvironment:- gravitee_management_mongodb_uri=mongodb://mongodb:27017/gravitee?serverSelectionTimeoutMS=5000&connectTimeoutMS=5000&socketTimeoutMS=5000- gravitee_analytics_elasticsearch_endpoints_0=http://elasticsearch:9200networks: [gio_storage, gio_front]management_ui:image: graviteeio/apim-management-ui:4.13.3restart: "no"ports: ['8084:8080']depends_on: [management_api]environment:- MGMT_API_URL=http://localhost:8083/management/networks: [gio_front] -
Start Gravitee
Terminal window docker compose -f gravitee/docker-compose.yml up -dGravitee’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 athost.docker.internal.
Set up Keycard
Section titled “Set up Keycard”Two scripts from the Kong recipe register Gravitee and the orders server in Keycard through the Management API, with your Service Account credential.
-
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.cloudexport MCP_RESOURCE=http://localhost:8082/orders/mcpexport ORDERS_RESOURCE=http://localhost:8091/mcpexport KONG_APP_IDENTIFIER=gravitee-gatewayexport KONG_CREDENTIAL_FILE=./gravitee-gateway.env./keycard/setup.sh./keycard/setup-exchange.shsetup.shregisters Gravitee’s endpoint,http://localhost:8082/orders/mcp, as a Resource with the scopemcp:tools.setup-exchange.shcreates the Applicationgravitee-gatewaythat Gravitee authenticates as when it exchanges tokens, saves its client ID and secret togravitee-gateway.env(git ignores it), and makes it the provider of Gravitee’s endpoint. It also registers the orders server as the Resourcehttp://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
exportlines they print, because the next steps use the variables you set here.
Start the MCP server
Section titled “Start the MCP server”-
Run the orders server
In a new terminal, from the repository root:
Terminal window export KEYCARD_ISSUER=https://<zone-id>.keycard.cloudexport GATEWAY_CLIENT_ID=$(sed -n 's/^KONG_KEYCARD_CLIENT_ID=//p' gravitee-gateway.env)export ORDERS_RESOURCE=http://localhost:8091/mcp PORT=8091cd orders-mcpuv run orders-mcpIt listens on
http://localhost:8091/mcpand accepts a token only if Keycard issued it for this server to Gravitee’s Application. Leave it running.
Create the API in Gravitee
Section titled “Create the API in Gravitee”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.
-
Set the Management API URLs and Gravitee’s Keycard credential
Back in the first terminal, where
KEYCARD_ISSUERis still set:Terminal window export GRAVITEE_MGMT=http://localhost:8083/management/v2/environments/DEFAULTexport GRAVITEE_ORG=http://localhost:8083/management/organizations/DEFAULT/environments/DEFAULTset -a; . ./gravitee-gateway.env; set +aexport KEYCARD_BASIC="Basic $(printf '%s:%s' "$KONG_KEYCARD_CLIENT_ID" "$KONG_KEYCARD_CLIENT_SECRET" | base64 | tr -d '\n')" -
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.JsonSlurperimport groovy.json.JsonOutputimport io.gravitee.policy.groovy.PolicyResult.Statedef server = context.getAttribute('kc.server')def body = request.contentdef msg = nullif (body != null && body.trim()) {try { msg = new JsonSlurper().parseText(body) } catch (Exception e) { msg = 'UNPARSEABLE' }}def detail = nulldef bad = nullif (msg instanceof List) {bad = 'Send one JSON-RPC message per request'} else if (msg instanceof Map && msg.method instanceof String) {def m = msg.methodif (m == 'tools/call') {def n = (msg.params instanceof Map) ? msg.params.name : nullif (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.FAILUREresult.code = 400result.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 : '')) -
Save the API definition
Save this as
gravitee/orders-api.json. The script, the token endpoint URL, and theAuthorizationvalue 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": []}]} -
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) -
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 -
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 -
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 -
Start and deploy the API
Terminal window curl -sS --fail-with-body -u admin:admin -X POST "$GRAVITEE_MGMT/apis/$API_ID/_start" > /dev/nullcurl -sS --fail-with-body -u admin:admin -H 'Content-Type: application/json' -d '{"deploymentLabel":"keycard"}' \"$GRAVITEE_MGMT/apis/$API_ID/deployments" > /dev/nullGravitee now serves the API at
http://localhost:8082/orders/mcp.
Check Gravitee without a token
Section titled “Check Gravitee without a token”-
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 theresource_metadatain itsWWW-Authenticateheader ishttp://localhost:8082/orders/mcp/.well-known/oauth-protected-resource. -
Read the metadata
Terminal window curl -s http://localhost:8082/orders/mcp/.well-known/oauth-protected-resourceThe metadata names your Keycard issuer:
{"resource":"http://localhost:8082/orders/mcp","authorization_servers":["https://<zone-id>.keycard.cloud"],"scopes_supported":["mcp:tools"]}
Connect Claude Code and sign in
Section titled “Connect Claude Code and sign in”-
Add the server to Claude Code
Terminal window claude mcp add --transport http gravitee-orders http://localhost:8082/orders/mcpclaude -
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. -
Check the result
Claude Code connects and lists the orders server’s two tools,
list_ordersandrefund_order. The MCP server’s terminal showsaccepted a token for sub=<user-id> from the gatewayfor each request Gravitee forwarded.Keycard’s Audit Log records your sign-in and a
credentials:issuewith theauthorization_codegrant, issued to you through the client Claude Code registered. After that comes onecredentials:issuewith the token exchange grant for each MCP request, issued to you through Gravitee’s Application. Each of those records carries theauthorization_detailsGravitee sent.
Verify
Section titled “Verify”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.
-
Run the script
In the first terminal, where
ORDERS_RESOURCEis still set:Terminal window export POLICY_SET_NAME=gravitee-tutorial./keycard/block-refunds.shIt ends with
Activated gravitee-tutorial with orders-no-refunds. -
List the orders
Ask Claude to list the orders. Keycard allows
list_orders, so Claude lists three orders: A-1001 and A-1003 areshipped, and A-1002 ispending. -
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.
-
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 acredentials:issuefailure with the same reason.
To give refunds back, activate default-zone-policies again in Console.
How the Gravitee config fits together
Section titled “How the Gravitee config fits together”Sign-in, in the keycard-jwt plan:
- Setting
publicKeyResolvertoJWKS_URLwithresolverParameterset to<keycard-issuer-url>/openidconnect/jwksmakes 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 the401it sends a request without a valid token. - Gravitee advertises
requiredScopesasscopes_supportedin that metadata. SettingcheckRequiredScopes: falsemakes 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, thenaud, thenclient_id. Keycard’s tokens have noazp, so Gravitee matches onaud, which is Gravitee’s endpoint URL, and admits every caller through the onekeycard-callersapplication.
The exchange, in the keycard-exchange flow, which Gravitee runs on every request:
- In the Set server step, Gravitee sets
kc.serverto 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’stargetis where Gravitee sends the request. - In the Groovy policy, Gravitee reads the JSON-RPC message and builds the token exchange request with one
authorization_detailsentry: the tool fortools/call, the method fortools/list,prompts/list,resources/list, andresources/templates/list, andinitializefor 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.shmakes Gravitee’s Application the provider of Gravitee’s endpoint. - When Keycard answers with an error, setting
exitOnErrormakes Gravitee stop the request and answer403witherrorContent: Keycard’serror_descriptionafterKeycard refused this call:, with its double quotes replaced by single quotes. TheCALLOUT_EXIT_ON_ERRORresponse 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
Authorizationheader 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.
Clean up
Section titled “Clean up”docker compose -f gravitee/docker-compose.yml stoprm gravitee-gateway.envStop 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.
Limits
Section titled “Limits”- 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
Authorizationheader, 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.
Troubleshooting
Section titled “Troubleshooting”- If refunds still work after you ran
block-refunds.shagain, the script stopped because theorders-no-refundspolicy already exists. Activate thegravitee-tutorialPolicy Set in Console instead. - If a refusal reaches Claude Code wrapped in
{"message": ..., "http_status_code": 403}, the API has noCALLOUT_EXIT_ON_ERRORresponse template. Run step 7 of Create the API in Gravitee again, then thedeploymentscommand from step 8. - If a batch request, or a
tools/callwithout a valid tool name, gets403withMissing 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 eachtools/call. - If the orders server logs
refused a token issued to client <client-id>, not the gateway,GATEWAY_CLIENT_IDisn’t the client ID ingravitee-gateway.env. Set it again and restart the server.