Get upstream credentials through agentgateway
Let agentgateway trade each caller's Keycard token for a GitHub or Google credential on the way to the MCP server, with each route allowed only its own upstream.
MCP servers behind a gateway often need a credential for an upstream API, such as a GitHub token for a GitHub MCP server. In this recipe agentgateway asks Keycard for that credential on every call with an RFC 8693 token exchange, so no upstream token is stored in the gateway or the MCP server.
- MCP client Calls a gateway route, such as
/github/mcp, with the person’s Keycard token. - agentgateway Checks the token, then sends it to Keycard and asks for a credential for that route’s upstream API.
- Keycard Checks that the gateway may reach that upstream for this person, and returns the person’s credential for it.
- GitHub API Receives the call with the person’s own GitHub credential. The Keycard token never reaches it.
Prerequisites
Section titled “Prerequisites”- The setup from Connect agentgateway to Keycard, with the gateway running.
- A Service Account with a Management API token in
ACCESS_TOKEN. Follow Add a credential and Use the credential if you don’t have one. - The upstream API Resources registered in Keycard with their OAuth Providers. The Keycard setup section of the delegated access guide adds GitHub from the catalog, and Google Calendar follows the same steps. This recipe calls them
<github-api-resource-id>and<calendar-api-resource-id>.
Register the gateway as an Application
Section titled “Register the gateway as an Application”The gateway needs its own identity, so Keycard can check that the gateway provides the route the caller’s token was issued for.
-
Create the Application
Terminal window curl -s -X POST https://api.keycard.ai/zones/<zone-id>/applications \-H "Authorization: Bearer $ACCESS_TOKEN" \-H "Content-Type: application/json" \-d '{"name": "agentgateway","identifier": "agentgateway"}' | jq '{id, name}'Note the
idfrom the response as<gateway-app-id>. -
Create a client credential
In Keycard Console, open the agentgateway Application. On its Application Credentials tab, click Add credential, and choose Client ID & Secret. The gateway authenticates its token exchanges with it.
Give each route its own Resource and upstream
Section titled “Give each route its own Resource and upstream”By default an Application’s dependencies apply to every Resource it provides, so a person who signs in to the GitHub route would also be asked to consent to Google Calendar. The when_accessing parameter on a dependency names the routes it applies to.
flowchart LR
subgraph gw["agentgateway Application"]
R1["Resource<br/>/github/mcp"]
R2["Resource<br/>/calendar/mcp"]
end
R1 -->|"dependency<br/>when_accessing: /github/mcp"| U1["https://api.github.com"]
R2 -->|"dependency<br/>when_accessing: /calendar/mcp"| U2["https://www.googleapis.com/calendar/v3"]
-
Create one Resource per route
Terminal window ZONE_PROVIDER_ID=$(curl -s "https://api.keycard.ai/zones/<zone-id>/providers?type=keycard-sts" \-H "Authorization: Bearer $ACCESS_TOKEN" | jq -r '.items[0].id')Create the GitHub route Resource:
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\": \"GitHub MCP (gateway)\",\"identifier\": \"http://localhost:3000/github/mcp\",\"scopes\": [\"mcp:tools\"],\"credential_provider_id\": \"$ZONE_PROVIDER_ID\",\"application_id\": \"<gateway-app-id>\"}" | jq '{id, identifier}'Repeat for the calendar route with identifier
http://localhost:3000/calendar/mcp. Note the twoidvalues as<github-route-resource-id>and<calendar-route-resource-id>. -
Add each upstream as a dependency of its route
The dependency endpoint takes the upstream Resource ID in the path and the route Resource ID in the
when_accessingquery parameter. The request has no body.Terminal window curl -s -X PUT "https://api.keycard.ai/zones/<zone-id>/applications/<gateway-app-id>/dependencies/<github-api-resource-id>?when_accessing=<github-route-resource-id>" \-H "Authorization: Bearer $ACCESS_TOKEN" -i | head -1curl -s -X PUT "https://api.keycard.ai/zones/<zone-id>/applications/<gateway-app-id>/dependencies/<calendar-api-resource-id>?when_accessing=<calendar-route-resource-id>" \-H "Authorization: Bearer $ACCESS_TOKEN" -i | head -1Both return
204 No Content. Keycard picks the dependencies for a route this way:- A route named by at least one dependency gets only the dependencies that name it.
- A route that no dependency names gets every dependency of the Application, including those that name other routes. Give each new route at least one dependency that names it.
- To share one upstream across routes, repeat
when_accessingin the same request, once for each route. EachPUTreplaces the dependency’swhen_accessinglist with the one it sends.
Check the dependencies Keycard will use when a User signs in to the GitHub route:
Terminal window curl -s "https://api.keycard.ai/zones/<zone-id>/applications/<gateway-app-id>/dependencies?when_accessing=<github-route-resource-id>" \-H "Authorization: Bearer $ACCESS_TOKEN" | jq '.items[] | {identifier, when_accessing}'Only the GitHub API appears:
{"identifier": "https://api.github.com","when_accessing": ["<github-route-resource-id>"]}
Configure the exchange for each route
Section titled “Configure the exchange for each route”-
Write the route config
In
config.yaml, give each route anmcpAuthenticationpolicy for that route’s Resource, and give each MCP target abackendAuth.oauthTokenExchangepolicy whoseresourcesnames the upstream API. Save the client secret togateway-client-secret.txtin your working directory.# yaml-language-server: $schema=https://agentgateway.dev/schema/configgateways:default:port: 3000routes:- matches:- path:exact: /github/mcp- path:exact: /.well-known/oauth-protected-resource/github/mcppolicies:cors:allowOrigins: ['*']allowHeaders: [mcp-protocol-version, content-type, authorization]exposeHeaders: [Mcp-Session-Id]mcpAuthentication:mode: strictissuer: <keycard-issuer-url>audiences:- http://localhost:3000/github/mcpjwks:url: <keycard-issuer-url>/openidconnect/jwksresourceMetadata:resource: http://localhost:3000/github/mcpscopesSupported:- mcp:toolsbearerMethodsSupported:- headerbackends:- mcp:targets:- name: githubmcp:host: <github-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.txtgrantType: tokenExchange# The gateway strips the caller's token after validating it,# so use the validated JWT as the subject token.subjectToken:source:expression: 'jwt.rawToken.unredacted()'# Must match the upstream API's Resource identifier in Keycard.resources:- https://api.github.comauthorizationLocation:header:name: authorizationprefix: "Bearer "cache:maxEntries: 8192defaultTtl: 300sAdd a second route for
/calendar/mcpthat mirrors this one, withaudiences,resource, andresourcesset to the calendar route andhttps://www.googleapis.com/calendar/v3. Replace<keycard-issuer-url>,<zone-id>,<gateway-client-id>, and<github-mcp-server-url>with your values.After checking the caller’s token, the gateway removes it from the request, so the
Authorizationheader is empty by the time the exchange runs. SettingsubjectTokentojwt.rawToken.unredacted()makes the gateway use the checked token instead.
Verify
Section titled “Verify”-
Sign in to the GitHub route
Terminal window claude mcp add --transport http github http://localhost:3000/github/mcpRun
/mcp, select github, then Authenticate. The consent screen asks you to approve the GitHub route and GitHub through the gateway. It doesn’t mention Google Calendar, because that dependency names only the calendar route. -
Call a GitHub tool
Approve the consent screen and ask Claude to use a GitHub tool. The gateway exchanges your token for a GitHub credential and forwards the call.
Clean up
Section titled “Clean up”- Remove the routes from Claude Code:
claude mcp remove github, and the same for the calendar route if you added it. - In Keycard Console, delete the two route Resources and the agentgateway Application.
- Delete
gateway-client-secret.txt.
Limits
Section titled “Limits”when_accessingcan’t be set in Console yet. Use the Management API or the Terraform provider.- A token from the Keycard CLI doesn’t carry consent to the gateway’s upstreams, so test each route from an MCP client.
- Keycard checks policy and the person’s grants again on every exchange, so taking access away in Keycard applies to the next exchange. The gateway reuses an exchanged credential for up to
defaultTtl, 300 seconds in this config.
Troubleshooting
Section titled “Troubleshooting”- If the gateway answers
400on every call through a route with an exchange, check thatsubjectTokenis set tojwt.rawToken.unredacted(), as in Configure the exchange for each route. - If the exchange fails with
User consent is required., the token likely came from the Keycard CLI, which doesn’t ask for consent to the gateway’s upstreams. Sign in to the route from an MCP client instead. - If the GitHub route’s consent screen also asks for Google Calendar, no dependency names the GitHub route, so it gets every dependency. Add
when_accessingfor it, as in Give each route its own Resource and upstream. - If an upstream you expected is missing from the token’s
targetclaim, look for a Deny under Policies → Activity. Keycard drops a dependency that policy denies rather than failing the sign-in. See soft denials at the token endpoint.