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.
- MCP client Calls a tool through agentgateway with the person’s Keycard token.
- agentgateway Checks the token and exchanges it with Keycard, naming the tool.
- Keycard Checks policy and issues a token for the MCP server, or refuses the exchange.
- MCP server Receives the call with the exchanged token, or never sees it while agentgateway returns
400“invalid request”.
Prerequisites
Section titled “Prerequisites”- 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_IDfrom 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
stdiotarget. This recipe calls the MCP endpoint<mcp-server-url>and usesquery_recordsfor reads andupdate_recordfor writes. Use your server’s tool names. - Claude Code or another OAuth-capable MCP client,
curl, andjq.
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.
Register the route and set policy
Section titled “Register the route and set policy”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.
-
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 itsidas<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
idas<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 -1The 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. -
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_idclaim isn’t<gateway-client-id>. For an Application that authenticates with a client secret, Keycard setsclient_idto that client ID. -
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-grantspolicy, or a copy of it, every tool is already permitted, so you only add aforbidfor 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_recordout.// 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.
Configure agentgateway
Section titled “Configure agentgateway”-
Configure the route
Add the route to the
routeslist inconfig.yaml, alongside your existing routes. Save the gateway’s client secret togateway-client-secret.txtif you haven’t already.routes:- name: recordsmatches:- path:exact: /records/mcp- path:exact: /.well-known/oauth-protected-resource/records/mcppolicies: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: strictissuer: <keycard-issuer-url>audiences:- http://localhost:3000/records/mcpjwks:url: <keycard-issuer-url>/openidconnect/jwksresourceMetadata:resource: http://localhost:3000/records/mcpbearerMethodsSupported:- headerbackends:- mcp:targets:- name: recordsmcp:host: <mcp-server-url>policies:backendAuth:oauthTokenExchange:host: <zone-id>.keycard.cloud:443path: /oauth/2/tokenpolicies:backendTLS: {}clientAuth:method: clientSecretBasicclientId: <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: 0additionalParams: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
authorizationrule. agentgateway reads the body of an MCP request for its expressions only when an expression on the route mentionsmcp, and the exchange’sadditionalParamsdon’t count. Without a rule like this one, every exchange goes out with no method or tool, and the call is checked asinitialize. subjectTokenfromjwt.rawToken.unredacted(). Without it the exchange finds no token, and the gateway answers400without asking Keycard.- The
authorization_detailsexpression. Atools/callnames the tool. Any other call names its method, and a method Keycard has no action for, such asserver/discover, which agentgateway sends beforeinitialize, is sent asinitialize. Keycard refuses an empty list.locationshas to name the same Resource asresources. This expression decides tools one by one and nothing else: a prompt or resource read (prompts/get,resources/read) also goes out asinitialize, so it’s allowed whereverinitializeis. cachewithmaxEntries: 0. The exchange cache keys on the caller’s token and everyadditionalParamsvalue, 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. - The route-level
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.
Verify
Section titled “Verify”-
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/mcpRun
/mcpin Claude Code, select records, then Authenticate, and sign in. Ask Claude to callquery_records: it works and returns your server’s tool result. -
Call a refused tool
Ask Claude to call
update_record: it fails, and Claude Code showsError 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
forbidin step 3. Under your own Policy Set, a tool with no permit is refused withUser "<email>" is not allowed to perform action "mcp::tools/call::update_record" on "Records MCP server"instead.
Clean up
Section titled “Clean up”-
Remove the route
Run
claude mcp remove records. Remove the records route fromconfig.yamland stop agentgateway if you started it for this recipe. Deletegateway-client-secret.txtif it is no longer needed. -
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.
Limits
Section titled “Limits”- 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/getandresources/readgo to Keycard asinitialize, so they pass whereverinitializeis permitted.
Troubleshooting
Section titled “Troubleshooting”- If every exchange is checked as
initialize, keep the route-levelauthorizationrule that mentionsmcp;additionalParamsalone doesn’t make agentgateway read the tool. - If agentgateway returns
400without an exchange in the Audit Log, check thatsubjectTokenreadsjwt.rawToken.unredacted(). - If agentgateway returns
500“backend authentication failed”, check the gateway’s client ID and client secret. Keycard returns401when 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.