Skip to content

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.

  1. MCP client Calls a gateway route, such as /github/mcp, with the person’s Keycard token.
  2. agentgateway Checks the token, then sends it to Keycard and asks for a credential for that route’s upstream API.
  3. Keycard Checks that the gateway may reach that upstream for this person, and returns the person’s credential for it.
  4. GitHub API Receives the call with the person’s own GitHub credential. The Keycard token never reaches it.
  • 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>.

The gateway needs its own identity, so Keycard can check that the gateway provides the route the caller’s token was issued for.

  1. 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 id from the response as <gateway-app-id>.

  2. 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"]
  1. 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 two id values as <github-route-resource-id> and <calendar-route-resource-id>.

  2. 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_accessing query 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 -1
    curl -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 -1

    Both 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_accessing in the same request, once for each route. Each PUT replaces the dependency’s when_accessing list 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>"]
    }
  1. Write the route config

    In config.yaml, give each route an mcpAuthentication policy for that route’s Resource, and give each MCP target a backendAuth.oauthTokenExchange policy whose resources names the upstream API. Save the client secret to gateway-client-secret.txt in your working directory.

    # yaml-language-server: $schema=https://agentgateway.dev/schema/config
    gateways:
    default:
    port: 3000
    routes:
    - matches:
    - path:
    exact: /github/mcp
    - path:
    exact: /.well-known/oauth-protected-resource/github/mcp
    policies:
    cors:
    allowOrigins: ['*']
    allowHeaders: [mcp-protocol-version, content-type, authorization]
    exposeHeaders: [Mcp-Session-Id]
    mcpAuthentication:
    mode: strict
    issuer: <keycard-issuer-url>
    audiences:
    - http://localhost:3000/github/mcp
    jwks:
    url: <keycard-issuer-url>/openidconnect/jwks
    resourceMetadata:
    resource: http://localhost:3000/github/mcp
    scopesSupported:
    - mcp:tools
    bearerMethodsSupported:
    - header
    backends:
    - mcp:
    targets:
    - name: github
    mcp:
    host: <github-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
    grantType: 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.com
    authorizationLocation:
    header:
    name: authorization
    prefix: "Bearer "
    cache:
    maxEntries: 8192
    defaultTtl: 300s

    Add a second route for /calendar/mcp that mirrors this one, with audiences, resource, and resources set to the calendar route and https://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 Authorization header is empty by the time the exchange runs. Setting subjectToken to jwt.rawToken.unredacted() makes the gateway use the checked token instead.

  1. Sign in to the GitHub route

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

    Run /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.

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

  1. Remove the routes from Claude Code: claude mcp remove github, and the same for the calendar route if you added it.
  2. In Keycard Console, delete the two route Resources and the agentgateway Application.
  3. Delete gateway-client-secret.txt.
  • when_accessing can’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.
  • If the gateway answers 400 on every call through a route with an exchange, check that subjectToken is set to jwt.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_accessing for it, as in Give each route its own Resource and upstream.
  • If an upstream you expected is missing from the token’s target claim, 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.

Did this recipe work for you?