Skip to content

Decide each tool call behind agentgateway

Let Keycard allow or refuse each tool call behind agentgateway by exchanging the caller's token once per call.

agentgateway checks the caller’s Keycard token before forwarding MCP calls. In this recipe, agentgateway exchanges that token once per call and names the tool, so Keycard policy decides whether the call reaches the MCP server.

  1. MCP client Calls a tool through agentgateway with the person’s Keycard token.
  2. agentgateway Checks the token and exchanges it with Keycard, naming the tool.
  3. Keycard Checks policy and issues a token for the MCP server, or refuses the exchange.
  4. MCP server Receives the call with the exchanged token, or never sees it while agentgateway returns 400 “invalid request”.
  • A Keycard organization where you have the Admin Role.
  • agentgateway. Tested with agentgateway v1.7.0.
  • The gateway Application and its client credential from Register the gateway as an Application.
  • ZONE_PROVIDER_ID from the Create one Resource per route step in Give each route its own Resource and upstream.
  • A Service Account with a Management API token in ACCESS_TOKEN. Follow Add a credential and Use the credential.
  • Your issuer URL from Settings → Connection, called <keycard-issuer-url> here, and your <zone-id> for API paths and the exchange host.
  • An HTTP MCP server that validates tokens Keycard issues. Build an MCP server creates one. agentgateway can’t add a credential to a stdio target. This recipe calls the MCP endpoint <mcp-server-url> and uses query_records for reads and update_record for writes. Use your server’s tool names.
  • Claude Code or another OAuth-capable MCP client, curl, and jq.

This recipe assumes the managed default-zone-policies Policy Set is active. If you use your own Policy Set, the policy step below includes explicit permits instead.

Each exchange names the MCP method or tool as an RFC 9396 authorization detail:

[{"type": "mcp", "action": "tools/call", "name": "update_record", "locations": ["<mcp-server-url>"]}]

Keycard checks that detail as Keycard::Action::"mcp::tools/call::update_record" on the Resource in locations. A call without a tool, such as tools/list, is checked as Keycard::Action::"mcp::tools/list". Keycard first checks every exchange with Keycard::Action::"any", so a call needs a permit for both. See Allow or deny specific tools.

  1. Register the route and the MCP server

    Create a Resource for a new route, provided by the gateway Application, as in the Create one Resource per route step in Give each route its own Resource and upstream, with the identifier http://localhost:3000/records/mcp. Note its id as <records-route-resource-id>.

    Register the MCP server as a Resource on the Provider identified by ZONE_PROVIDER_ID, with its MCP endpoint as the identifier:

    Terminal window
    curl -s -X POST https://api.keycard.ai/zones/<zone-id>/resources \
    -H "Authorization: Bearer $ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d "{
    \"name\": \"Records MCP server\",
    \"identifier\": \"<mcp-server-url>\",
    \"credential_provider_id\": \"$ZONE_PROVIDER_ID\"
    }" | jq '{id, identifier}'

    Note its id as <mcp-server-resource-id>, and declare it as a dependency of the gateway, scoped to the route:

    Terminal window
    curl -s -X PUT "https://api.keycard.ai/zones/<zone-id>/applications/<gateway-app-id>/dependencies/<mcp-server-resource-id>?when_accessing=<records-route-resource-id>" \
    -H "Authorization: Bearer $ACCESS_TOKEN" -i | head -1

    The route’s Resource has to be provided by the gateway Application. Keycard lets only the Application that provides a Resource exchange a token issued for it, and refuses any other client with Client is not allowed to exchange token for this resource.

  2. Have the MCP server accept only the gateway’s tokens

    A token from the exchange doesn’t say which tool it was issued for. A caller who got a token for the MCP server some other way could call any tool with it, and skip the per-tool check. After the usual issuer and audience checks, have the server also reject any token whose client_id claim isn’t <gateway-client-id>. For an Application that authenticates with a client secret, Keycard sets client_id to that client ID.

  3. Decide each tool in policy

    Each tool call is an action on the MCP server’s Resource, Keycard::Action::"mcp::tools/call::<tool-name>", and policy treats it like any other action. In Policies, duplicate the managed default-zone-policies Policy Set as Agentgateway Access, then use Add policy… → Create new policy and the Cedar editor to add the policy below. If you use your own Policy Set, add the explicit permits below to that set instead.

    If your Policy Set includes the managed default-user-grants policy, or a copy of it, every tool is already permitted, so you only add a forbid for each tool to take away. See Block one tool, leave the rest.

    @id("records-no-writes")
    forbid (
    principal,
    action == Keycard::Action::"mcp::tools/call::update_record",
    resource
    ) when {
    resource.identifier == "<mcp-server-url>"
    };

    If your Policy Set doesn’t include the managed policies, permit each step yourself: signing in to the route, the gateway’s exchange on the User’s behalf, the calls MCP clients make on connect, and the tools. Anything you don’t permit is refused, so this set leaves update_record out.

    // Sign-in: Users may authorize the route, and clients registered through
    // Dynamic Client Registration may get a token for it on their behalf.
    @id("records-route-signin")
    permit ( principal is Keycard::User, action, resource )
    when { resource.identifier == "http://localhost:3000/records/mcp" };
    @id("records-route-dcr-client")
    permit ( principal is Keycard::Application, action, resource )
    when {
    principal.registration_method == Keycard::RegistrationMethod::"dcr" &&
    resource.identifier == "http://localhost:3000/records/mcp" &&
    context.on_behalf == true
    };
    // Exchange: the gateway may trade the User's token for the MCP server,
    // only on their behalf. The User's rules below decide each tool.
    @id("records-gateway-exchange")
    permit ( principal is Keycard::Application, action, resource )
    when {
    principal.identifier == "agentgateway" &&
    resource.identifier == "<mcp-server-url>" &&
    context.on_behalf == true
    };
    // The Zone checks every exchange with "any" before the tool, so the
    // User needs this as well as a permit for each tool.
    @id("records-user-grant")
    permit ( principal is Keycard::User,
    action == Keycard::Action::"any",
    resource )
    when { resource.identifier == "<mcp-server-url>" };
    // Calls MCP clients make on connect. They're listed one by one so the
    // set works on every Policy schema version, including ones with no
    // MCPProtocol group.
    @id("records-protocol")
    permit ( principal is Keycard::User,
    action in [Keycard::Action::"mcp::initialize", Keycard::Action::"mcp::tools/list",
    Keycard::Action::"mcp::prompts/list", Keycard::Action::"mcp::resources/list",
    Keycard::Action::"mcp::resources/templates/list"],
    resource )
    when { resource.identifier == "<mcp-server-url>" };
    @id("records-read")
    permit ( principal is Keycard::User,
    action == Keycard::Action::"mcp::tools/call::query_records",
    resource )
    when { resource.identifier == "<mcp-server-url>" };

    Replace the placeholders before you publish: the Policy API refuses Cedar that contains angle brackets. Validate and Save each policy, then Activate the Policy Set.

The dependency request returns 204 No Content. The MCP server now accepts only tokens issued to the gateway, and policy permits reads but refuses writes.

  1. Configure the route

    Add the route to the routes list in config.yaml, alongside your existing routes. Save the gateway’s client secret to gateway-client-secret.txt if you haven’t already.

    routes:
    - name: records
    matches:
    - path:
    exact: /records/mcp
    - path:
    exact: /.well-known/oauth-protected-resource/records/mcp
    policies:
    cors:
    allowOrigins: ['*']
    allowHeaders: [mcp-protocol-version, content-type, authorization]
    exposeHeaders: [Mcp-Session-Id]
    # Always passes. It mentions mcp so the gateway reads each MCP
    # request; the exchange below needs the method and tool from it.
    authorization:
    rules:
    - require: 'has(mcp.methodName) || true'
    mcpAuthentication:
    mode: strict
    issuer: <keycard-issuer-url>
    audiences:
    - http://localhost:3000/records/mcp
    jwks:
    url: <keycard-issuer-url>/openidconnect/jwks
    resourceMetadata:
    resource: http://localhost:3000/records/mcp
    bearerMethodsSupported:
    - header
    backends:
    - mcp:
    targets:
    - name: records
    mcp:
    host: <mcp-server-url>
    policies:
    backendAuth:
    oauthTokenExchange:
    host: <zone-id>.keycard.cloud:443
    path: /oauth/2/token
    policies:
    backendTLS: {}
    clientAuth:
    method: clientSecretBasic
    clientId: <gateway-client-id>
    clientSecret:
    file: gateway-client-secret.txt
    # mcpAuthentication removes the token once it has
    # validated it, so read the validated token instead.
    subjectToken:
    source:
    expression: 'jwt.rawToken.unredacted()'
    resources:
    - <mcp-server-url>
    cache:
    maxEntries: 0
    additionalParams:
    authorization_details: >-
    has(mcp.tool)
    ? '[{"type":"mcp","action":"tools/call","name":"' + mcp.tool.name + '","locations":["<mcp-server-url>"]}]'
    : '[{"type":"mcp","action":"'
    + (has(mcp.methodName) && mcp.methodName in ['initialize', 'tools/list', 'prompts/list', 'resources/list', 'resources/templates/list'] ? mcp.methodName : 'initialize')
    + '","locations":["<mcp-server-url>"]}]'

    Replace <keycard-issuer-url>, <zone-id>, <gateway-client-id>, and <mcp-server-url> with your values. Four settings make this part work:

    • The route-level authorization rule. agentgateway reads the body of an MCP request for its expressions only when an expression on the route mentions mcp, and the exchange’s additionalParams don’t count. Without a rule like this one, every exchange goes out with no method or tool, and the call is checked as initialize.
    • subjectToken from jwt.rawToken.unredacted(). Without it the exchange finds no token, and the gateway answers 400 without asking Keycard.
    • The authorization_details expression. A tools/call names the tool. Any other call names its method, and a method Keycard has no action for, such as server/discover, which agentgateway sends before initialize, is sent as initialize. Keycard refuses an empty list. locations has to name the same Resource as resources. This expression decides tools one by one and nothing else: a prompt or resource read (prompts/get, resources/read) also goes out as initialize, so it’s allowed wherever initialize is.
    • cache with maxEntries: 0. The exchange cache keys on the caller’s token and every additionalParams value, so tokens for different tools never mix. A cached token does outlive a policy change, though, so leave the cache off while you test policy and turn it back on afterward if you want it.

    Write the route out in full as above. With agentgateway’s top-level mcp: shorthand and no route policy, the exchange doesn’t see the tool.

Run agentgateway with agentgateway -f config.yaml, or save the file for a running gateway to reload it. The gateway serves the records route on port 3000.

  1. Call an allowed tool

    Point an MCP client at the route and sign in:

    Terminal window
    claude mcp add --transport http records http://localhost:3000/records/mcp

    Run /mcp in Claude Code, select records, then Authenticate, and sign in. Ask Claude to call query_records: it works and returns your server’s tool result.

  2. Call a refused tool

    Ask Claude to call update_record: it fails, and Claude Code shows Error POSTing to endpoint: invalid request.

    In Keycard, Audit Log has the refused token exchange, with a message that names the policy:

    Action "mcp::tools/call::update_record" on "Records MCP server" is denied by Policy "records-no-writes" in version <version> of Policy Set "<policy-set-name>".

    That message comes from the forbid in step 3. Under your own Policy Set, a tool with no permit is refused with User "<email>" is not allowed to perform action "mcp::tools/call::update_record" on "Records MCP server" instead.

  1. Remove the route

    Run claude mcp remove records. Remove the records route from config.yaml and stop agentgateway if you started it for this recipe. Delete gateway-client-secret.txt if it is no longer needed.

  2. Remove the Keycard configuration

    Restore the previously active Policy Set and remove the policies or Policy Set you created for this recipe. Delete the records route Resource and the Records MCP server Resource, including the scoped dependency. Keep the gateway Application and its credential if other routes still use them.

  • The format agentgateway uses to name the tool in its exchange request, an RFC 9396 authorization detail, is provisional and may change.
  • The token Keycard issues for the MCP server doesn’t say which tool it was issued for, so the MCP server has to accept only tokens issued to the gateway’s Application. See Bring your own MCP server.
  • agentgateway returns every refusal from Keycard as 400 “invalid request” without Keycard’s reason. The reason is in the Audit Log.
  • With cache maxEntries: 0, every call is its own decision and a round trip to Keycard.
  • The expression names tools only. prompts/get and resources/read go to Keycard as initialize, so they pass wherever initialize is permitted.
  • If every exchange is checked as initialize, keep the route-level authorization rule that mentions mcp; additionalParams alone doesn’t make agentgateway read the tool.
  • If agentgateway returns 400 without an exchange in the Audit Log, check that subjectToken reads jwt.rawToken.unredacted().
  • If agentgateway returns 500 “backend authentication failed”, check the gateway’s client ID and client secret. Keycard returns 401 when that credential is refused.
  • If Keycard says Client is not allowed to exchange token for this resource, make the gateway Application the route Resource’s provider.

Did this recipe work for you?