Decide each tool call behind Kong AI Gateway
Put an MCP server behind Kong AI Gateway with Keycard sign-in, and let Keycard policy allow or refuse each tool call.
Kong AI Gateway can sit in front of an MCP server as the place access is enforced, with Keycard deciding each tool call. Kong asks Keycard about every MCP request and forwards it 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 Kong with a token for Kong’s endpoint.
- Kong AI Gateway Checks the token, 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 Kong answers
403with Keycard’s reason.
Prerequisites
Section titled “Prerequisites”- The recipe’s repository, keycardai/tutorial-kong-mcp, cloned. Run the commands on this page from its root unless a step says otherwise.
- A Konnect account and a personal access token in
KONNECT_TOKEN - kongctl:
brew install --formula kong/kongctl/kongctl - 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, Python 3.12 or later, and uv
- An MCP client. This recipe uses Claude Code.
This recipe was tested with Kong AI Gateway 2.3.0, kongctl 1.26.0, FastMCP 4.1.6, and Claude Code 2.1.319.
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 Kong. See Access Policies.
Start Kong
Section titled “Start Kong”scripts/kong-dataplane.sh creates an AI Gateway in Konnect and runs a local data plane for it in Docker on port 8000. These are the steps Kong’s AI quickstart takes, written out.
-
Run the data plane script
Terminal window ./scripts/kong-dataplane.sh -
Export the AI Gateway ID
The script prints
export AI_GATEWAY_ID=.... Run that line.
Set up Keycard
Section titled “Set up Keycard”Two scripts register Kong 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.cloud./keycard/setup.sh./keycard/setup-exchange.shsetup.shregisters Kong’s endpoint,http://localhost:8000/orders/mcp, as a Resource with the scopemcp:tools.setup-exchange.shcreates the Application that Kong authenticates as when it exchanges tokens, saves its client ID and secret tokong-gateway.env(git ignores it), and registers the orders server as the Resourcehttp://localhost:8090/mcp. -
Run the export lines
Both scripts end with
exportlines for the next steps. Run them.
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' kong-gateway.env)cd orders-mcpuv run orders-mcpIt listens on
http://localhost:8090/mcpand accepts a token only if Keycard issued it for this server to Kong’s Application. Leave it running.
Apply the Kong config
Section titled “Apply the Kong config”With kong/kong.yaml, Kong signs callers in with Keycard and exchanges their token on every request. How the Kong config fits together explains each setting.
-
Apply the config
Back in the first terminal:
Terminal window set -a; . ./kong-gateway.env; set +aexport KONG_KEYCARD_BASIC="Basic $(printf '%s:%s' "$KONG_KEYCARD_CLIENT_ID" "$KONG_KEYCARD_CLIENT_SECRET" | base64 | tr -d '\n')"export ORDERS_MCP_URL=http://host.docker.internal:8090/mcpexport KONGCTL_DEFAULT_KONNECT_PAT="$KONNECT_TOKEN"kongctl adopt ai-gateway "${AI_GATEWAY_NAME:-kong-keycard-tutorial}" --namespace kong-keycard-tutorialkongctl apply -f kong/kong.yaml --auto-approveKonnect pushes the config to the data plane within a few seconds.
Check Kong without a token
Section titled “Check Kong without a token”-
Send a request without a token
Terminal window curl -i -X POST http://localhost:8000/orders/mcp \-H 'content-type: application/json' \-H 'accept: application/json, text/event-stream' \-d '{"jsonrpc":"2.0","method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1.0"}},"id":1}'Kong answers
401, and theWWW-Authenticateheader points at its protected resource metadata:HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer realm="<zone-id>.keycard.cloud", resource_metadata="http://localhost:8000/.well-known/oauth-protected-resource/orders/mcp", scope="mcp:tools", error="invalid_token" -
Read the metadata
Terminal window curl -s http://localhost:8000/.well-known/oauth-protected-resource/orders/mcpThe metadata names your Keycard issuer:
{"resource":"http://localhost:8000/orders/mcp","scopes_supported":["mcp:tools"],"authorization_servers":["https://<zone-id>.keycard.cloud"]}
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 orders http://localhost:8000/orders/mcpclaude -
Sign in
Run
/mcp, select orders, then Authenticate. Claude Code reads Kong’s metadata, registers with Keycard, and opens Keycard’s sign-in page. Sign in, then ask Claude to list the orders.If Claude Code has connected to this URL before with a different Keycard issuer, choose Clear authentication before Authenticate. Otherwise it can keep using tokens from the old issuer, and Kong rejects them.
-
Check the result
Keycard’s default policies allow every tool, so Claude lists three orders. The MCP server’s terminal shows
accepted a token for sub=<user-id> from the gatewayfor each request Kong forwarded.In Keycard Console, the Audit Log shows 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 Kong’s Application.
Verify
Section titled “Verify”Take one tool away and check that Kong refuses it while the other keeps working. keycard/block-refunds.sh copies Keycard’s default policies as the Policy Set kong-tutorial, adds a policy that forbids refund_order, and activates the copy.
-
Run the script
Terminal window ./keycard/block-refunds.sh -
Ask for a refund
Ask Claude to refund order A-1002. Kong answers
403, and Claude shows Keycard’s reason: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 "kong-tutorial".The version number can differ.
-
List the orders again
Ask Claude to list the orders again: listing still works, and 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. To take them away again, activate kong-tutorial in Console. Running block-refunds.sh a second time doesn’t do it, because the script stops when the orders-no-refunds policy already exists.
Watch the exchanges (optional)
Section titled “Watch the exchanges (optional)”scripts/exchange-logger.py sits between Kong and Keycard and logs each exchange Kong sends, with tokens shown only as fingerprints.
-
Start the logger
Terminal window KEYCARD_TOKEN_URL=https://<zone-id>.keycard.cloud/oauth/2/token python3 scripts/exchange-logger.py -
Point Kong at the logger
Run the
kongctl applyfrom Apply the Kong config again withKEYCARD_TOKEN_URL=http://host.docker.internal:8099/oauth/2/token. For each exchange Kong sends, the logger prints one JSON line with theauthorization_details, Keycard’s status and any error, and fingerprints of the tokens, and appends it toexchange-log.jsonl. -
Point Kong back at Keycard
Point
KEYCARD_TOKEN_URLback at your issuer URL when you’re done.
How the Kong config fits together
Section titled “How the Kong config fits together”Sign-in, in the keycard AI Auth Strategy and the MCP server:
issueris your Keycard issuer URL, andjwks_endpointis<keycard-issuer-url>/openidconnect/jwks, where Keycard publishes its signing keys.audience_requiredis the Resource identifier, so Kong refuses a token Keycard issued for a different Resource.access.metadataon the MCP server makes Kong serve protected resource metadata and check the token’s audience.resourcehas to equal the Resource identifier in Keycard exactly, including the/orders/mcppath.- Setting
hide_credentials: falsemakes Kong keep the caller’s token on the request, so it can send that token to Keycard in the exchange. Kong then replaces it, so the caller’s token never reaches the MCP server.
The exchange, in the keycard-exchange Request Callout:
- In
request.by_lua, Kong reads the JSON-RPC message and names what it asks Keycard about: 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, but not other methods. Kong answers a batch, or atools/callwithout a valid tool name, with400before it asks Keycard. serverat the top of that Lua is the orders server’s Resource identifier. Change it there if yours is different.- Kong sends its own client ID and secret in the callout’s
Authorizationheader. Only the Application that provides a Resource can exchange tokens issued for it, sosetup-exchange.shmakes Kong’s Application the provider of Kong’s endpoint. - Setting
cache.bypass: truemakes Kong ask Keycard on every request, so each call gets its own decision. - In
upstream.by_lua, Kong swaps in the token Keycard issued, or answers403with Keycard’s reason.
Clean up
Section titled “Clean up”docker rm -f "${AI_GATEWAY_NAME:-kong-keycard-tutorial}-gateway"rm kong-gateway.envDelete the AI Gateway in Konnect. In Keycard Console, activate default-zone-policies again, then remove the kong-tutorial Policy Set, the Kong AI Gateway Application, and both Resources if you no longer need them.
Limits
Section titled “Limits”- The format Kong uses to name the tool in its exchange request, an RFC 9396 authorization detail, is provisional and may change.
- Kong 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 Kong’s Application, so nothing reaches it without Kong’s per-call decision.
- Kong’s Datakit policy can make the exchange without Lua, but a refusal then reaches the client as a generic
500without Keycard’s reason. - Kong’s client secret is part of the policy’s config in Konnect, so anyone who can read this AI Gateway’s config can read it.
Troubleshooting
Section titled “Troubleshooting”- If Kong rejects Claude Code’s token after you changed Keycard organizations, Claude Code is still using a token from the old issuer. Choose Clear authentication, then Authenticate again.
- If refunds still work after you ran
block-refunds.shagain, the script stopped because theorders-no-refundspolicy already exists. Activate thekong-tutorialPolicy Set in Console instead. - If a call gets
400before Kong asks Keycard, the request was a batch, or atools/callwithout a valid tool name.