Skip to content

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.

  1. MCP client Signs the person in through Keycard and calls a tool through Kong with a token for Kong’s endpoint.
  2. Kong AI Gateway Checks the token, 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 Kong answers 403 with Keycard’s reason.
  • 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 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, 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.

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.

  1. Run the data plane script

    Terminal window
    ./scripts/kong-dataplane.sh
  2. Export the AI Gateway ID

    The script prints export AI_GATEWAY_ID=.... Run that line.

Two scripts register Kong 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
    ./keycard/setup.sh
    ./keycard/setup-exchange.sh

    setup.sh registers Kong’s endpoint, http://localhost:8000/orders/mcp, as a Resource with the scope mcp:tools. setup-exchange.sh creates the Application that Kong authenticates as when it exchanges tokens, saves its client ID and secret to kong-gateway.env (git ignores it), and registers the orders server as the Resource http://localhost:8090/mcp.

  2. Run the export lines

    Both scripts end with export lines for the next steps. Run them.

  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' kong-gateway.env)
    cd orders-mcp
    uv run orders-mcp

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

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.

  1. Apply the config

    Back in the first terminal:

    Terminal window
    set -a; . ./kong-gateway.env; set +a
    export 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/mcp
    export KONGCTL_DEFAULT_KONNECT_PAT="$KONNECT_TOKEN"
    kongctl adopt ai-gateway "${AI_GATEWAY_NAME:-kong-keycard-tutorial}" --namespace kong-keycard-tutorial
    kongctl apply -f kong/kong.yaml --auto-approve

    Konnect pushes the config to the data plane within a few seconds.

  1. 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 the WWW-Authenticate header points at its protected resource metadata:

    HTTP/1.1 401 Unauthorized
    WWW-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"
  2. Read the metadata

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

    The metadata names your Keycard issuer:

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

    Terminal window
    claude mcp add --transport http orders http://localhost:8000/orders/mcp
    claude
  2. 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.

  3. 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 gateway for each request Kong forwarded.

    In Keycard Console, the Audit Log shows 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 Kong’s Application.

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.

  1. Run the script

    Terminal window
    ./keycard/block-refunds.sh
  2. 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.

  3. 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 a credentials:issue failure 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.

scripts/exchange-logger.py sits between Kong and Keycard and logs each exchange Kong sends, with tokens shown only as fingerprints.

  1. Start the logger

    Terminal window
    KEYCARD_TOKEN_URL=https://<zone-id>.keycard.cloud/oauth/2/token python3 scripts/exchange-logger.py
  2. Point Kong at the logger

    Run the kongctl apply from Apply the Kong config again with KEYCARD_TOKEN_URL=http://host.docker.internal:8099/oauth/2/token. For each exchange Kong sends, the logger prints one JSON line with the authorization_details, Keycard’s status and any error, and fingerprints of the tokens, and appends it to exchange-log.jsonl.

  3. Point Kong back at Keycard

    Point KEYCARD_TOKEN_URL back at your issuer URL when you’re done.

Sign-in, in the keycard AI Auth Strategy and the MCP server:

  • issuer is your Keycard issuer URL, and jwks_endpoint is <keycard-issuer-url>/openidconnect/jwks, where Keycard publishes its signing keys.
  • audience_required is the Resource identifier, so Kong refuses a token Keycard issued for a different Resource.
  • access.metadata on the MCP server makes Kong serve protected resource metadata and check the token’s audience. resource has to equal the Resource identifier in Keycard exactly, including the /orders/mcp path.
  • Setting hide_credentials: false makes 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 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, but not other methods. Kong answers a batch, or a tools/call without a valid tool name, with 400 before it asks Keycard.
  • server at 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 Authorization header. Only the Application that provides a Resource can exchange tokens issued for it, so setup-exchange.sh makes Kong’s Application the provider of Kong’s endpoint.
  • Setting cache.bypass: true makes 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 answers 403 with Keycard’s reason.
Terminal window
docker rm -f "${AI_GATEWAY_NAME:-kong-keycard-tutorial}-gateway"
rm kong-gateway.env

Delete 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.

  • 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 500 without 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.
  • 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.sh again, the script stopped because the orders-no-refunds policy already exists. Activate the kong-tutorial Policy Set in Console instead.
  • If a call gets 400 before Kong asks Keycard, the request was a batch, or a tools/call without a valid tool name.

Did this recipe work for you?