Help improve this page
To contribute to this user guide, choose the Edit this page on GitHub link that is located in the right pane of every page.
Call third-party APIs from agents without giving them credentials
A third-party API key or OAuth token in an agent’s pod is exposed to everything that runs there, including model-generated code, which can read it and use it from anywhere the agent can reach. Gateway custody removes that exposure. The gateway holds the credential and attaches it to requests from the agent it belongs to, and network policy lets the agent reach only the gateway, so the agent can use the API without ever seeing the credential.
Custody has a cost. Every call takes a hop through the gateway, and the gateway becomes the store for every agent’s third-party authority, which is why Considerations treats it as the highest-value target in the stack. It also moves access control. The agent reaches the API only while the gateway admits it, so you revoke one agent’s access by changing the gateway’s rule for that agent, without rotating a token that other agents share. Turn on the gateway in Route agent egress through a gateway first.
The examples use GitHub. Slack, Google, and Atlassian follow the same pattern.
The following diagrams show each path.
- Open source
-
The following diagram shows the open source path. The consent receiver runs the OAuth flow and stores the agent’s token in AWS Secrets Manager. AgentGateway reads the token from a synced Kubernetes Secret and attaches it to the agent’s requests.
-
AWS services
-
The following diagram shows the AWS services path. The consent receiver starts the OAuth flow and completes the session binding after a person approves. AgentCore Gateway attaches the credential from AgentCore Identity.
Open source and AWS services paths
Both gateways keep the credential out of agent pods, but they store it, attach it, and decide which agents may use it differently. The following table compares how each path provides third-party credentials.
| Property |
Open source |
AWS services |
|
Gateway
|
AgentGateway
|
AgentCore Gateway, part of Amazon Bedrock AgentCore
|
|
Credential store
|
AWS Secrets Manager, synced into the gateway’s namespace as a Kubernetes Secret
|
The token vault of AgentCore Identity, part of Amazon Bedrock AgentCore
|
|
Destination declared as
|
A third_party_credentials entry that names the host and its one caller
|
A credential provider, plus an open_api_targets entry that turns an OpenAPI document into MCP tools
|
|
Access token attached to
|
Every request for the destination host
|
Calls to an OpenAPI target’s tools, through a credential provider
|
|
OAuth consent
|
A consent receiver in the reference sample runs the authorization code flow, because the open source gateway has none
|
Built into AgentCore Gateway. The consent receiver completes the session binding that AgentCore requires
|
|
Allowed agents
|
One named caller per destination. Other agents get 403
|
The agents that a Cedar policy names
|
The open source gateway selects a credential by destination host, so each host carries one credential. Two agents that need different authority on the same service would need per-user credentials, which that gateway doesn’t support. The managed gateway attaches credentials per target and exposes the API as MCP tools, so an agent can call only the operations the target’s schema describes.
How each path is configured
- Open source
-
Each third_party_credentials entry names a destination host and the one agent, caller, that can use it. For each entry, Terraform creates an AWS Secrets Manager secret and syncs it into the gateway’s namespace as a Kubernetes Secret, and the gateway gets a route for the host that attaches the credential and admits only caller. Terraform doesn’t set the secret’s value. You store it as JSON {"token": "…"}, either directly or through a consent flow.
An oauth_consent entry, under the same key as its third_party_credentials entry, deploys the consent receiver, which writes the approved token into that entry’s secret. client_secret_arn names the secret that holds the OAuth app’s client secret. Leave scopes unset for a GitHub App, whose permissions come from the app and its installation.
-
AWS services
-
AgentCore Gateway stores the credential in the AgentCore Identity token vault and attaches it per target. A credential provider tells AgentCore Identity where a credential comes from. An api_key_providers entry points at an existing Secrets Manager secret and the JSON key inside it, and Terraform never sets the secret’s value. An oauth2_providers entry holds an OAuth app’s client ID and the secret that stores its client secret. The gateway’s role can read only its own workload identity and the providers that these entries create, by name. A provider that you create outside the stack isn’t readable by the gateway until you declare it here.
An open_api_targets entry turns the endpoints in an OpenAPI 3 document into MCP tools, and its credential block names the provider whose credential the gateway attaches to each call. Every response media type in the schema must be JSON, XML, or form data, because a target whose schema includes a text/plain response is created and then fails. A Cedar policy names the agents that can call the target, and agents that it doesn’t name don’t see the target’s tools. See Write gateway policy.
For OAuth consent, AgentCore Gateway runs the flow but sends the browser back to a return URL that must complete the session binding with the identity that started the flow, which is the agent’s service account token. No browser holds that token, so an agentcore_consent entry deploys the consent receiver to complete the binding for one agent. Its tool names a tool on the target that the receiver calls as the agent to start the flow, and the target’s default_return_url points at the receiver.
Choose how the credential is issued
Two credential types fit agents, and they differ in whose authority the agent carries.
| Credential |
When to use it |
What it carries |
|
Access token or API key
|
The agent acts as one fixed identity, such as a service account or a bot.
|
The authority of whoever created the token, limited to the repositories and permissions you select.
|
|
OAuth consent (GitHub App)
|
The agent acts with a person’s authority, granted once in a browser.
|
The intersection of the app’s permissions, the repositories you install it on, and the approving person’s own access. The token expires after 8 hours and is refreshed.
|
A personal access token is the simpler choice. You create it once and scope it to the repositories and permissions the agent needs, and the agent acts as the identity that owns it. Everything the agent does is attributed to that identity, and the token lasts until it expires or you revoke it. Start with a fine-grained personal access token.
OAuth consent lets the agent act with a specific person’s authority, granted once in a browser. The token is bounded by both the app’s permissions and the person’s own access, and it expires and is refreshed, so a leaked token is short-lived. The cost is an interactive approval, plus a component that receives it, stores the token, and refreshes it. Use OAuth consent only when the agent must act as a specific person.
For OAuth consent, use a GitHub App. A GitHub App’s token is limited to the repositories the app is installed on, and it expires. An OAuth App’s token carries all of the person’s access. See Differences between GitHub Apps and OAuth apps in the GitHub documentation.
Per-user credentials aren’t covered
The gateway stores one consented token per agent. It identifies the caller by the agent’s service account token, so a consented token belongs to the agent it was granted for. Calling the API with each end user’s own authority requires that user’s identity to reach the gateway on every call. This guide doesn’t cover that pattern.
Prerequisites
-
The gateway, turned on with enable_gateway = true. See Route agent egress through a gateway.
-
Terraform and your variables file, and a shell with kubectl access to the cluster, on the bastion or your workstation.
-
PAVED_PATH set to open-source or aws-services, such as with export PAVED_PATH=open-source.
-
AWS credentials that can create and update secrets in AWS Secrets Manager. set-credential.sh stores every credential and OAuth client secret there.
-
In GitHub, permission to create a fine-grained personal access token, or to register a GitHub App and install it on the target repositories.
-
For OAuth consent with a bastion, the Session Manager plugin on your workstation. consent.sh forwards through the bastion. In workstation mode, it port-forwards locally and needs no plugin.
Step 1: Declare the destination and provide the credential
Run the commands on this page from the agents directory of your clone of the reference sample, sample-eks-docs/agents. In the commands that take --cluster, replace my-agents with the name in your variables file. The script names each secret after it, and the stack’s roles can read only secrets with that prefix.
- Open source
-
Declare the destination first. This creates the secret, the route, and the caller rule for api.github.com, as described in How each path is configured. Do it for either credential type.
-
Add the destination to your variables file:
third_party_credentials = {
github = { destination = "api.github.com", caller = "research" }
}
-
Apply and sync:
./scripts/apply.sh --root terraform/open-source -var-file=my.tfvars
./scripts/run-stack.sh --root terraform/open-source -- ./scripts/bootstrap-gitops.sh --path open-source --sync
The bootstrap script applies the root Application with the values that the apply rendered, refreshes and syncs it, and waits for the Applications to converge. The apply creates the secret, its sync into the gateway’s namespace, and the route.
The secret is empty until you store a credential later in this step, so the sync ends with a line that names the secret and the command that sets it, and the gateway’s secret syncer waits for that value. Destinations that already have a credential keep working. Every other Application reports Synced and Healthy. If one stays Progressing after its objects are ready, run the bootstrap script again, because Argo CD can keep the health it computed while they were starting. See Turn on a component later.
The agent calls the gateway’s in-cluster endpoint with the destination in the Host header and its projected token in the Authorization header:
import httpx
# The kubelet rotates this file, so read it on every call.
def gateway_token():
return open("/var/run/secrets/eks-agents/gateway/token").read().strip()
httpx.get("http://egress.agentgateway-system.svc.cluster.local:8080/repos/OWNER/REPO",
headers={"Host": "api.github.com", "Authorization": f"Bearer {gateway_token()}"})
Then store one of the two credential types.
Personal access token
-
Create a fine-grained token in GitHub. Choose Only select repositories and only the repository permissions the agent needs, such as Contents read-only. See Managing your personal access tokens.
-
Store the token. The script asks for it at a hidden prompt, so it isn’t in your shell history:
./scripts/set-credential.sh --cluster my-agents --region region-code token github
The script stores the token as {"token": "…"} in the Secrets Manager secret my-agents/agentgateway/github, then restarts the gateway’s secret syncer so the gateway picks up the new value. At the value for token github (hidden): prompt, paste the token, which starts with github_pat_. The script refuses a value that looks like an OAuth client secret. The restart needs kubectl access to the cluster. If kubectl can’t reach the cluster from where you run the script, as with the default private endpoint, the script stores the token and prints the restart command. Run it in a shell on the bastion, as described in Where commands run.
OAuth consent
-
Register a GitHub App. See Registering a GitHub App.
-
Set Callback URL to http://localhost:8765/callback/github. Keep Expire user authorization tokens selected. Clear Webhook > Active. Under Repository permissions, choose only what the agent needs. A private key is not needed.
-
Copy the Client ID. You add it to your variables file in step 5, and it doesn’t go to the script. Then generate a client secret, and store it with the following command. The script asks for the secret at a hidden prompt, so it isn’t in your shell history:
./scripts/set-credential.sh --cluster my-agents --region region-code oauth-client github
The script stores the secret as my-agents/consent/github-oauth-client and prints the line oauth_consent.github.client_secret_arn = "<ARN>" for step 5. At the value for oauth-client github (hidden): prompt, paste the client secret that you generated in the app’s settings, under General > Client secrets. It’s 40 hexadecimal characters, and GitHub shows it only once. Don’t paste the Client ID. The script refuses a value that looks like a token.
-
Install the app on the repositories the agent needs.
-
Add the consent to your variables file, using the Client ID from step 3 and the client_secret_arn line that the script printed, and apply. This deploys the consent receiver for the github entry. See How each path is configured.
oauth_consent = {
github = {
client_id = "Iv23..."
client_secret_arn = "arn:aws:secretsmanager:..."
authorize_url = "https://github.com/login/oauth/authorize"
token_url = "https://github.com/login/oauth/access_token"
}
}
The apply creates the consent receiver’s Amazon ECR repository but not its image, so build it, then sync. The build pushes only images whose repository is new and skips the rest:
./scripts/build-images.sh --root terraform/open-source
./scripts/run-stack.sh --root terraform/open-source -- ./scripts/bootstrap-gitops.sh --path open-source --sync
Without the image, the receiver’s pod stays in ImagePullBackOff and the sync waits for it.
-
Approve once from your workstation. The consent receiver has no Service, so you reach it only through kubectl port-forward, which requires cluster authentication. With a bastion, the script forwards through it. In workstation mode, it port-forwards from your workstation, bound to 127.0.0.1:
./scripts/consent.sh --cluster my-agents --region region-code github
Open http://localhost:8765/connect/github and approve.
The receiver stores the access token. It keeps the refresh token where only the receiver can read it, and refreshes both before the access token expires.
-
AWS services
-
You declare the credential provider and the target together, as described in How each path is configured. Store one of the two credential types.
Personal access token
-
Create a fine-grained token in GitHub, scoped as described in the Open source tab, and store it:
./scripts/set-credential.sh --path aws-services --cluster my-agents --region region-code token githubpat
At the value for token githubpat (hidden): prompt, paste the token, which starts with github_pat_. The script stores it as {"token": "…"} in the Secrets Manager secret my-agents/agentcore/githubpat, which the provider in the next step names.
-
Declare an API key credential provider and the target, and apply:
api_key_providers = {
githubpat = { secret_id = "my-agents/agentcore/githubpat", json_key = "token" }
}
open_api_targets = {
githubpat = {
description = "GitHub REST with a gateway-held token."
schema_inline = "..." # an OpenAPI 3 document for the endpoints, servers: https://api.github.com
credential = { kind = "api_key", provider = "githubpat" }
}
}
OAuth consent
AgentCore Gateway runs the authorization code flow and stores the token. The consent receiver starts the flow as the agent and completes the session binding.
The gateway returns the consent URL through MCP URL elicitation, which requires MCP version 2025-11-25 on the gateway and on each request. The sample configures the gateway’s supported versions. After consent is granted, clients on earlier MCP versions can call the tool.
-
Register a GitHub App and install it on the repositories the agent needs, as described in the Open source tab. Step 4 adds the callback URL that AgentCore Identity issues.
-
Store the GitHub App’s client secret. At the value for oauth-client github (hidden): prompt, paste the client secret from the app’s settings, under General > Client secrets, not the Client ID:
./scripts/set-credential.sh --path aws-services --cluster my-agents --region region-code oauth-client github
The script stores the secret as {"client_secret": "…"} in my-agents/consent/github-oauth-client, which the provider in the next step names in secret_id.
-
Declare the provider, an authorization-code target, and the consent, and apply. The consent entry deploys the receiver that completes the session binding for the research agent:
oauth2_providers = {
github = { vendor = "GithubOauth2", client_id = "Iv23...", secret_id = "my-agents/consent/github-oauth-client" }
}
open_api_targets = {
githuboauth = {
description = "GitHub REST with the agent's consented token."
schema_inline = "..."
credential = {
kind = "oauth"
provider = "github"
grant_type = "AUTHORIZATION_CODE"
default_return_url = "http://localhost:8765/complete/github"
}
}
}
agentcore_consent = {
github = { agent = "research", tool = "githuboauth___getAuthenticatedUser" }
}
The apply creates the consent receiver’s Amazon ECR repository but not its image, so build it, then sync. The build pushes only images whose repository is new and skips the rest:
./scripts/build-images.sh --root terraform/aws-services
./scripts/run-stack.sh --root terraform/aws-services -- ./scripts/bootstrap-gitops.sh --path aws-services --sync
Without the image, the receiver’s pod stays in ImagePullBackOff and the sync waits for it.
-
Add the callback URL that AgentCore Identity issued for the provider to the GitHub App. A GitHub App accepts up to 10 callback URLs, so one app can serve both paths:
terraform -chdir=terraform/aws-services output oauth2_callback_urls
-
Approve once with ./scripts/consent.sh --cluster my-agents --region region-code github, and open http://localhost:8765/connect/github. The receiver calls the target’s tool as the agent and sends your browser to GitHub’s consent page. After you approve, AgentCore returns the browser to /complete/github, and the receiver completes the binding with the same agent token.
The session binding completes, and the agent’s next call to the target’s tools uses the consented token.
Step 2: Verify
Run each check from inside the agent’s pod, so it uses the agent’s identity and network policy. Confirm the following:
-
A call through the gateway succeeds.
GET /user returns the identity that owns the credential.
-
The same call from an agent you didn’t name fails. The open source path returns 403. On the AWS services path, Cedar policy denies it.
-
A direct call to api.github.com fails. If it succeeds, the agent can bypass the gateway. See Restrict agent egress with network policy.
-
The agent’s environment contains no GitHub token.
The following steps run all four checks with a short script that you send to the agent’s container. Run them from the agents directory. The commands use the reference agent research as the agent you named. Replace other-agent with the name of an agent that the destination or the Cedar policy doesn’t name.
- Open source
-
-
Save the check as check-github.py. The script calls GET /user through AgentGateway, then dials api.github.com directly:
import os, re, httpx
# The agent's projected token for the gateway. The kubelet rotates the file, so read it now.
token = open("/var/run/secrets/eks-agents/gateway/token").read().strip()
r = httpx.get("http://egress.agentgateway-system.svc.cluster.local:8080/user",
headers={"Host": "api.github.com", "Authorization": f"Bearer {token}"}, timeout=30)
login = r.json().get("login") if r.status_code == 200 else ""
print("through the gateway:", r.status_code, login, "rate limit", r.headers.get("x-ratelimit-limit"))
try:
httpx.get("https://api.github.com/user", timeout=5)
print("direct call: SUCCEEDED, the agent can bypass the gateway")
except httpx.HTTPError as exc:
print("direct call: refused,", type(exc).__name__)
leaked = [k for k, v in os.environ.items() if re.match(r"(github_pat_|ghp_|ghu_|gho_)", v)]
print("GitHub tokens in the environment:", leaked or "none")
-
Run the script as the agent you named. --file sends the script to where the command runs:
./scripts/run-stack.sh --root terraform/open-source --file check-github.py -- \
bash -c "kubectl -n agents exec -i research -c agent -- python3 - < check-github.py"
The gateway call returns 200 with the login of the GitHub user who owns the credential. Its rate limit is the authenticated limit, 5000, not the anonymous 60. The direct call is refused and the environment holds no GitHub token.
-
Run the same script as an agent that the destination doesn’t name:
./scripts/run-stack.sh --root terraform/open-source --file check-github.py -- \
bash -c "kubectl -n agents exec -i other-agent -c agent -- python3 - < check-github.py"
The gateway call returns 403.
-
AWS services
-
-
Save the check as check-github.py. The gateway exposes each credential as a tool, so the script calls the target’s getAuthenticatedUser tool through AgentCore Gateway with MCP tools/call. Set TOOL to your target’s name followed by
_getAuthenticatedUser_getAuthenticatedUser:
import json, os, re, httpx
TOOL = "githubpat___getAuthenticatedUser"
mcp = os.environ["AGENT_MCP_URL"]
token = open("/var/run/secrets/eks-agents/gateway/token").read().strip()
h = {"Authorization": f"Bearer {token}", "Content-Type": "application/json",
"Accept": "application/json, text/event-stream"}
def rpc(body):
r = httpx.post(mcp, headers=h, json=body, timeout=30)
if "text/event-stream" in r.headers.get("content-type", ""):
data = [l[5:].strip() for l in r.text.splitlines() if l.startswith("data:")]
return r, json.loads(data[-1]) if data else {}
return r, r.json()
r, _ = rpc({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "check", "version": "1"}}})
if r.headers.get("mcp-session-id"):
h["Mcp-Session-Id"] = r.headers["mcp-session-id"]
rpc({"jsonrpc": "2.0", "method": "notifications/initialized"})
_, res = rpc({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": TOOL, "arguments": {}}})
print("through the gateway:", json.dumps(res.get("result") or res.get("error"))[:300])
try:
httpx.get("https://api.github.com/user", timeout=5)
print("direct call: SUCCEEDED, the agent can bypass the gateway")
except httpx.HTTPError as exc:
print("direct call: refused,", type(exc).__name__)
leaked = [k for k, v in os.environ.items() if re.match(r"(github_pat_|ghp_|ghu_|gho_)", v)]
print("GitHub tokens in the environment:", leaked or "none")
-
Run the script as the agent you named. --file sends the script to where the command runs:
./scripts/run-stack.sh --root terraform/aws-services --file check-github.py -- \
bash -c "kubectl -n agents exec -i research -c agent -- python3 - < check-github.py"
The tool’s result contains the login of the GitHub user who owns the credential. The direct call is refused and the environment holds no GitHub token.
-
Run the same script as an agent that the Cedar policy doesn’t name:
./scripts/run-stack.sh --root terraform/aws-services --file check-github.py -- \
bash -c "kubectl -n agents exec -i other-agent -c agent -- python3 - < check-github.py"
The result is an error that names the Cedar denial, denied by default, or the tool isn’t listed for that agent.
Clean up
Removing a destination stops the gateway from attaching its credential. The stored credential and any consented token are secrets in AWS Secrets Manager, outside the Terraform state, so they stay until you delete them. For the general steps, see Turn on a component later.
- Open source
-
-
Remove the destination’s third_party_credentials entry and any oauth_consent entry under the same key from your variables file.
-
Apply with scripts/apply.sh, and sync with pruning, which also removes the consent receiver when no oauth_consent entry remains:
./scripts/run-stack.sh --root terraform/open-source -- ./scripts/bootstrap-gitops.sh --path open-source --sync --prune
-
Delete the secrets that set-credential.sh created, if you no longer need them. Replace key with the destination’s key:
aws secretsmanager delete-secret --region region-code --secret-id my-agents/agentgateway/key
aws secretsmanager delete-secret --region region-code --secret-id my-agents/consent/key-oauth-client
-
Revoke the access at the provider. For a GitHub personal access token, delete the token in GitHub. For OAuth consent, revoke the app’s authorization, or uninstall the GitHub App from the repositories you installed it on.
-
AWS services
-
-
Remove the destination’s api_key_providers or oauth2_providers entry, the gateway target that uses it, and any agentcore_consent entry for it from your variables file.
-
Apply with scripts/apply.sh, and sync with pruning, which also removes the consent receiver when no agentcore_consent entry remains:
./scripts/run-stack.sh --root terraform/aws-services -- ./scripts/bootstrap-gitops.sh --path aws-services --sync --prune
-
Delete the secrets that set-credential.sh created, if you no longer need them. Replace key with the destination’s key:
aws secretsmanager delete-secret --region region-code --secret-id my-agents/agentcore/key
aws secretsmanager delete-secret --region region-code --secret-id my-agents/consent/key-oauth-client
-
Revoke the access at the provider. For a GitHub personal access token, delete the token in GitHub. For OAuth consent, revoke the app’s authorization, or uninstall the GitHub App from the repositories you installed it on.
The reference sample’s teardown script deletes these secrets when you remove the whole stack. See Clean up.