For the complete documentation index, see llms.txt. Markdown versions of all docs pages are available by appending .md to any docs URL.
Agent (upstream-only)
Let an agent that already has a downstream token get a user’s upstream OAuth credential, with only the upstream authorization in a browser.
Use agent elicitation to let an agent that already has a downstream token get a user’s upstream OAuth credential. The agent does not sign in through the gateway’s OAuth issuer. Only the upstream provider’s authorization runs in a browser.
About agent elicitation
Agent elicitation is the upstream-only variant of brokered elicitations. The agent gets its own token from your identity provider (IdP) before it calls the gateway, so the gateway skips the downstream login. The user still must authorize the upstream provider one time as follows.
- The agent calls the gateway. The user has no stored upstream credential, so the security token service (STS) returns the upstream provider’s authorization URL.
- The user opens the URL in a browser and authorizes the upstream provider. The STS stores the upstream credential for the user.
- The agent retries the request. The gateway adds the stored upstream token to this request and to all later requests automatically. The user does not authorize again until the STS cannot refresh the credential.
The agent flow uses the same brokered.chainedAuth configuration as the chained flow, and no setting selects it.
For more information about how the agent flow compares with the other brokered flows, and to see a sample agent flow, see The agent flow (upstream-only).
Before you begin
Complete Set up brokered elicitation. Reuse its Keycloak, OAuth issuer route,
keycloak-jwksbackend, and Everything MCP server.Make sure that you have the following environment variables saved.
echo $GATEWAY_NAME echo $GATEWAY_URL echo $KEYCLOAK_URL echo $KEYCLOAK_ISSUER
Step 1: Set up the upstream provider
Create an upstream-mcp realm with a confidential client for the gateway in your IdP and an upstream account for the test user. The gateway uses this client to complete the upstream OAuth flow.
Note
This example uses a second realm in the example Keycloak as the upstream OAuth provider, so that you can complete the flow without an account at a third-party service. For a real provider, such as GitHub, register ${GATEWAY_URL}/oauth-issuer/callback/upstream as the callback URL.
Then in Step 3, use the provider’s client credentials and endpoints.
Create the realm for the upstream OAuth provider through the Keycloak REST API. The access token for the Keycloak administrator expires after 60 seconds, so get the token in the same command.
ADMIN_TOKEN=$(curl -fsS -X POST "${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token" \ -d grant_type=password -d client_id=admin-cli -d username=admin -d password=admin | jq -r .access_token) curl -fsS -X POST "${KEYCLOAK_URL}/admin/realms" \ -H "Authorization: Bearer ${ADMIN_TOKEN}" \ -H "Content-Type: application/json" \ -d @- <<EOF { "realm": "upstream-mcp", "enabled": true, "sslRequired": "none", "clients": [ { "clientId": "agw-upstream", "secret": "local-upstream-secret", "publicClient": false, "standardFlowEnabled": true, "directAccessGrantsEnabled": false, "redirectUris": ["${GATEWAY_URL}/oauth-issuer/callback/upstream"] } ], "users": [ { "username": "alice", "enabled": true, "email": "alice@example.com", "emailVerified": true, "firstName": "Alice", "lastName": "Upstream", "credentials": [ {"type": "password", "value": "alice-upstream-password", "temporary": false} ] } ] } EOFSetting Description clientIdandsecretThe confidential client that the gateway uses for the upstream OAuth flow. redirectUrisThe issuer’s upstream callback, ${GATEWAY_URL}/oauth-issuer/callback/upstream. Use the same host and port asgateway_config.base_urlin the brokered setup.usersCreates an upstream account for alicewith a password that is different from the downstream realm. The different password shows which realm asks for the login.Export the upstream issuer URL.
export UPSTREAM_ISSUER="${KEYCLOAK_URL}/realms/upstream-mcp" curl -fsS "${UPSTREAM_ISSUER}/.well-known/openid-configuration" | jq '{issuer, authorization_endpoint, token_endpoint}'The output lists the upstream realm’s authorization and token endpoints. In Step 3, the policy builds the same two endpoints from
$UPSTREAM_ISSUER. The user’s browser opens the authorization endpoint, and the controller calls the token endpoint, so make sure that both can reach this URL.
Step 2: Give the agent a downstream token
The agent gets its own token from the downstream IdP, outside the gateway. In this example, a local-agent client uses the OAuth password grant as a stand-in for the agent’s own login. Your agent can use any grant that returns a token for the user, such as the authorization code flow or the device authorization flow when it starts.
Add the
local-agentclient to thedownstream-mcprealm.ADMIN_TOKEN=$(curl -fsS -X POST "${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token" \ -d grant_type=password -d client_id=admin-cli -d username=admin -d password=admin | jq -r .access_token) curl -fsS -X POST "${KEYCLOAK_URL}/admin/realms/downstream-mcp/clients" \ -H "Authorization: Bearer ${ADMIN_TOKEN}" \ -H "Content-Type: application/json" \ -d @- <<'EOF' { "clientId": "local-agent", "publicClient": true, "standardFlowEnabled": false, "directAccessGrantsEnabled": true, "protocolMappers": [ { "name": "gateway-audience", "protocol": "openid-connect", "protocolMapper": "oidc-audience-mapper", "config": { "included.client.audience": "agw-issuer", "access.token.claim": "true" } } ] } EOFSetting Description publicClientanddirectAccessGrantsEnabledLet the example get a token with a username and password. Do not enable the password grant for a production client. protocolMappersAdds agw-issuerto the token audience. The MCP authentication policy requires this audience.Get a token for
aliceas the agent.export AGENT_TOKEN=$(curl -fsS -X POST "${KEYCLOAK_ISSUER}/protocol/openid-connect/token" \ -d grant_type=password -d client_id=local-agent \ -d username=alice -d password=alice-password -d scope=openid | jq -r .access_token)Note
Keycloak access tokens are valid for 5 minutes by default. If a later request returns
401 Unauthorized, repeat this command to get a new token.
Step 3: Configure the MCP resource
Create a backend, an elicitation policy, and a route for the agent’s MCP resource at /mcp/agent. This example uses the Everything MCP server from the brokered setup. The server ignores the upstream token, so you can use the example without a real upstream service.
Store the upstream client secret in a Secret.
kubectl create secret generic agent-upstream-oauth \ -n agentgateway-system \ --from-literal=client_secret=local-upstream-secretCreate the backend, the policy, and the HTTPRoute.
kubectl apply -f- <<EOF apiVersion: agentgateway.dev/v1alpha1 kind: AgentgatewayBackend metadata: name: agent-mcp namespace: agentgateway-system spec: mcp: targets: - name: everything static: host: downstream-mcp.agentgateway-system.svc.cluster.local port: 3001 path: /mcp protocol: StreamableHTTP policies: mcp: authentication: mode: Strict issuer: "${KEYCLOAK_ISSUER}" audiences: [agw-issuer] jwks: backendRef: group: agentgateway.dev kind: AgentgatewayBackend name: keycloak-jwks cacheDuration: 5m jwksPath: /realms/downstream-mcp/protocol/openid-connect/certs --- apiVersion: enterpriseagentgateway.solo.io/v1alpha1 kind: EnterpriseAgentgatewayPolicy metadata: name: agent-mcp-elicit namespace: agentgateway-system spec: targetRefs: - group: agentgateway.dev kind: AgentgatewayBackend name: agent-mcp backend: entElicitation: brokered: mcpResourcePath: /mcp/agent chainedAuth: oauth: clientId: agw-upstream clientSecretRef: name: agent-upstream-oauth authorizeUrl: "${UPSTREAM_ISSUER}/protocol/openid-connect/auth" accessTokenUrl: "${UPSTREAM_ISSUER}/protocol/openid-connect/token" scopes: [openid, profile] entTokenExchange: solo: elicitation: {} --- apiVersion: gateway.networking.k8s.io/v1 kind: HTTPRoute metadata: name: agent-mcp namespace: agentgateway-system spec: parentRefs: - name: ${GATEWAY_NAME} rules: - matches: - path: type: PathPrefix value: /mcp/agent backendRefs: - group: agentgateway.dev kind: AgentgatewayBackend name: agent-mcp EOFReview the following table to understand this configuration. For more information, see the API docs.
Field Description kind: AgentgatewayBackendA plain backend works for the agent flow. The OAuth issuer finds this resource through the chainedAuthsettings in the policy. The EnterpriseAgentgatewayBackend that the brokered setup uses is required only for a resource withoutchainedAuth.authenticationValidates the agent’s downstream token: the issuer, the agw-issueraudience, and the signature. The agent flow does not needresourceMetadata, because the agent does not discover the OAuth issuer. AddresourceMetadataand the two discovery path matches from brokered setup only if MCP clients that run the OAuth flow also connect to this resource.brokered.mcpResourcePathThe MCP path that the gateway protects. It must match the HTTPRoute path. chainedAuth.oauth.clientIdandclientSecretRefThe upstream client from Step 1. The Secret stores the value under the client_secretkey.chainedAuth.oauth.authorizeUrlandaccessTokenUrlThe upstream provider’s endpoints. To discover the endpoints and register a client dynamically instead, set only baseUrl, as in the consent screen guide.chainedAuth.oauth.scopesThe upstream scopes that the user authorizes. entTokenExchange.solo.elicitationSends the proxy’s token exchange to the STS elicitation endpoint and injects the stored upstream token into requests to the backend. Required for the agent flow. Verify that the policy attached to the backend.
kubectl -n agentgateway-system get enterpriseagentgatewaypolicy agent-mcp-elicit \ -o jsonpath='{.status.ancestors[0].conditions}' | jq -c '.[] | {type, status, message}'Example output:
{"type":"Accepted","status":"True","message":"Policy accepted"} {"type":"Attached","status":"True","message":"Attached to all targets"}
Step 4: Call the tool as the agent
Send MCP requests with the agent’s token, as an agent does.
Initialize an MCP session and include the agent’s downstream token that you got in Step 2. This request is similar to the request that an agent sends. Verify that the request does not succeed, because the user has no upstream credential for the MCP server yet.
curl -s -i -X POST "${GATEWAY_URL}/mcp/agent" \ -H "Authorization: Bearer ${AGENT_TOKEN}" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"local-agent","version":"1"}}}'The response is
400 Bad Requestwith the upstream authorization URL. The URL points to theupstream-mcprealm, not to the gateway’s issuer or thedownstream-mcprealm, because the agent already has a downstream token. Example output for a gateway at172.18.0.4:HTTP/1.1 400 Bad Request content-type: application/json {"url":"http://172.18.0.8:8080/realms/upstream-mcp/protocol/openid-connect/auth?client_id=agw-upstream&redirect_uri=http%3A%2F%2F172.18.0.4%3A80%2Foauth-issuer%2Fcallback%2Fupstream&response_type=code&scope=openid+profile&state=sUtGn859..."}If you enabled the consent screen, the URL is the gateway’s consent page,
${GATEWAY_URL}/oauth-issuer/consent?state=.... The consent page redirects to the upstream provider after the user clicks Continue.Open the URL from the response in a browser. Keycloak shows the
upstream-mcplogin page.Note
Each request without a stored credential returns a new URL. Use the URL from the most recent response.
Sign in as
alicewith the passwordalice-upstream-password. The browser returns to the gateway and shows Authorization complete.The STS stores the upstream credential under the backend’s resource key and the
subclaim of the agent’s token. The agent never gets the upstream token. On each later request, the proxy exchanges the agent’s token with the STS for the stored upstream token, and sends the upstream token as the bearer token to the MCP server. If the upstream provider returned a refresh token, the STS refreshes the upstream token when it expires.Repeat the initialize request and save the session ID from the
mcp-session-idresponse header.export MCP_SESSION_ID=$(curl -s -i -X POST "${GATEWAY_URL}/mcp/agent" \ -H "Authorization: Bearer ${AGENT_TOKEN}" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"local-agent","version":"1"}}}' \ | grep -i '^mcp-session-id' | awk '{print $2}' | tr -d '\r') echo "${MCP_SESSION_ID}"If the output is empty, the request did not succeed. Run the request without the
grepto see the response. A401 Unauthorizedmeans that the agent’s token expired. Repeat Step 2 to get a new token.Call the Echo tool and verify that you get back a response from the tool.
curl -s -X POST "${GATEWAY_URL}/mcp/agent" \ -H "Authorization: Bearer ${AGENT_TOKEN}" \ -H "Content-Type: application/json" \ -H "Accept: application/json, text/event-stream" \ -H "Mcp-Session-Id: ${MCP_SESSION_ID}" \ -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"message":"hello from the agent"}}}'Example output:
event: message data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"Echo: hello from the agent"}]}}Check the controller logs for the agent flow.
kubectl logs -n agentgateway-system deploy/enterprise-agentgateway --since=10m \ | grep -E 'starting agent elicitation|agent elicitation flow|served elicitation token'Example output, shortened:
{"level":"info","msg":"no usable credential for user; starting agent elicitation","user_id":{"Claim":"sub","Value":"dc1eee6b-..."},"resource":"agentgateway-system/agent-mcp","mcp_resource":"/mcp/agent"} {"level":"info","msg":"upstream callback processed for agent elicitation flow","user_id":"dc1eee6b-..."} {"level":"info","msg":"served elicitation token","user_id":"dc1eee6b-...","resource":"agentgateway-system/agent-mcp","elicitation_id":1}The
resourcevalue is the backend’s{namespace}/{name}, which is the key that the STS stores the upstream credential under. Theserved elicitation tokenmessage shows that the STS returned the stored upstream token to the proxy.
Handle the flow in your agent
The gateway does not deliver the authorization URL as an MCP elicitation request. Build the following behavior into the agent.
| Situation | What the gateway does | What the agent must do |
|---|---|---|
| The user has no stored upstream credential for the resource. | Returns 400 with {"url":"..."}. For an MCP backend, this response comes from the initialize request, because the gateway connects to the MCP server when the session opens. | Show the URL to the user, wait until the user completes the authorization, and then retry the request. |
| The agent’s downstream token expired. | Returns 401 Unauthorized from the MCP authentication policy. | Refresh or renew the downstream token. The gateway does not refresh the agent’s own token. |
| The stored upstream token is close to expiry. | Refreshes the upstream token with the stored refresh token, if the provider issued one. | Nothing. |
| The upstream token expired, and the gateway cannot refresh it. | Resets the elicitation and returns a new 400 with a new authorization URL. | Show the new URL to the user, the same as for the first authorization. |
Clean up
Remove this guide’s resources. Keep the shared issuer and IdP while another brokered guide uses them.
Delete the route, policy, backend, and Secret.
kubectl delete httproute agent-mcp -n agentgateway-system kubectl delete enterpriseagentgatewaypolicy agent-mcp-elicit -n agentgateway-system kubectl delete agentgatewaybackend agent-mcp -n agentgateway-system kubectl delete secret agent-upstream-oauth -n agentgateway-systemDelete the upstream realm and the
local-agentclient from Keycloak. If you clean up the shared infrastructure, deleting the example Keycloak removes them too.ADMIN_TOKEN=$(curl -fsS -X POST "${KEYCLOAK_URL}/realms/master/protocol/openid-connect/token" \ -d grant_type=password -d client_id=admin-cli -d username=admin -d password=admin | jq -r .access_token) curl -fsS -X DELETE "${KEYCLOAK_URL}/admin/realms/upstream-mcp" -H "Authorization: Bearer ${ADMIN_TOKEN}" AGENT_CLIENT_ID=$(curl -fsS "${KEYCLOAK_URL}/admin/realms/downstream-mcp/clients?clientId=local-agent" \ -H "Authorization: Bearer ${ADMIN_TOKEN}" | jq -r '.[0].id') curl -fsS -X DELETE "${KEYCLOAK_URL}/admin/realms/downstream-mcp/clients/${AGENT_CLIENT_ID}" -H "Authorization: Bearer ${ADMIN_TOKEN}"