How to give an AI agent an API key without putting it in the prompt
The short answer: the model should know that a credential exists and what it is for, and nothing more. The code behind a tool holds the value, uses it, and returns only the result. Below is why that matters, a worked example you can run, and the part most guides leave out: making sure the agent cannot simply read the key some other way.
Where does a key in an agent's context end up?
A key pasted into a prompt, a system prompt, a chat message or a tool's output becomes part of the conversation. From there it can end up in places you do not control:
- Transcripts on disk. Coding agents keep session history locally. Claude Code, for example, stores transcripts
"locally in plaintext" under
~/.claude/projects/, for 30 days by default (Claude Code data usage). Anything the model saw is in that file. - Saved settings. An agent that asks to run a command containing a key, and is told "don't ask again", may save
that command, key included, as a permission rule in a settings file. The Cloud Security Alliance
summarized research
that found 1,122 such files with secrets among 104,185 public copies of
.claude/settings.local.json. - Configuration files. GitGuardian's State of Secrets Sprawl 2026 counted 24,008 unique secrets exposed in MCP configuration files.
- The model's own output. A model can repeat what is in its context: in an answer, in a commit message, or to an attacker. Prompt injection, instructions hidden in a web page, file or email the agent reads, is the route OWASP ranks first for LLM applications (LLM01:2025), and OWASP says plainly that "it is unclear if there are fool-proof methods of prevention for prompt injection."
OWASP's guidance on system prompts is direct: "credentials, connection strings, etc. should not be contained within the system prompt language", and "the system prompt should not be considered a secret" (LLM07:2025). The same holds for every other part of the context.
How does an agent use a key it never sees?
Split the work between the model and the code around it:
| the model knows | the code holds |
|---|---|
that a tool list_invoices exists, and what it does |
the billing API key |
| the tool's arguments: a customer ID | how to decrypt the key, and where it is |
| the tool's result: a list of invoices | the HTTP request with the key in its header |
The tool's arguments never include the key, and its result never echoes it. The model decides what to do; the code does it with the credential.
A worked example: a tool that decrypts its key at call time
This example keeps the key encrypted at rest with the age encryption tool, to a key pair that belongs to the agent's runtime alone. Set it up once:
mkdir -p ~/.config/agent/secrets
# The agent runtime's own key pair. The secret half stays in this file.
age-keygen -o ~/.config/agent/identity.txt
# Encrypt the billing key to it. Paste the key at the prompt, so it is not in your shell history.
read -rs BILLING_KEY && printf '%s\n' "$BILLING_KEY" \
| age -r "$(age-keygen -y ~/.config/agent/identity.txt)" -o ~/.config/agent/secrets/billing-api-key.age
unset BILLING_KEY
(On version 1.4.0 and later of the age encryption tool this makes a post-quantum key. If the store you use expects a
classic X25519 key, add -pq=false; What is an age key? explains the difference.)
The tool, in Python with only the standard library:
import os
import re
import subprocess
import urllib.error
import urllib.request
API = os.environ.get("BILLING_API", "https://api.example.com")
IDENTITY = os.environ.get(
"AGENT_IDENTITY", os.path.expanduser("~/.config/agent/identity.txt"))
SECRETS = os.path.expanduser("~/.config/agent/secrets")
class _NoRedirect(urllib.request.HTTPRedirectHandler):
"""urllib copies the Authorization header to a redirect target. Refuse."""
def redirect_request(self, *args, **kwargs):
return None
_opener = urllib.request.build_opener(_NoRedirect)
def _reveal(name):
"""Decrypt one secret by name. Only this process ever holds the value."""
if not re.fullmatch(r"[a-z0-9-]+", name):
raise ValueError("bad secret name")
out = subprocess.run(
["age", "-d", "-i", IDENTITY, os.path.join(SECRETS, name + ".age")],
check=True, capture_output=True, text=True,
)
return out.stdout.strip()
def list_invoices(customer_id):
"""The tool the model calls. Its arguments and result hold no key."""
if not re.fullmatch(r"cus_[A-Za-z0-9]+", customer_id):
return "error: customer_id must look like cus_..."
key = _reveal("billing-api-key")
request = urllib.request.Request(
f"{API}/v1/invoices?customer={customer_id}",
headers={"Authorization": f"Bearer {key}"},
)
try:
with _opener.open(request, timeout=10) as response:
body = response.read().decode(errors="replace")
except urllib.error.HTTPError as err:
detail = err.read().decode(errors="replace").replace(key, "[redacted]")
body = f"error: HTTP {err.code}: {detail[:200]}"
return body.replace(key, "[redacted]")
Four details matter:
- The key is decrypted per call and lives only in the tool process's memory, not in an environment variable that every child process inherits.
- The arguments are validated. The model's input is untrusted. A customer ID that does not match the expected shape is refused before any request is made, and a secret name cannot climb out of the secrets folder.
- The result is scrubbed. Some APIs echo the credential back in an error. The key is replaced before the error is
shortened, so a key that straddles the cut cannot slip through half-redacted. We tested this against a local server
that returns the
Authorizationheader in a 401 body; the model's result readerror: HTTP 401: bad key Bearer [redacted]. Redaction only catches an exact echo, not an encoded one. - Redirects are refused. Python's
urllibcopies request headers,Authorizationincluded, to wherever a redirect points. We measured it: a 302 to a second local server delivered the bearer token there. The_NoRedirecthandler stops that; the redirect comes back as an error the model can see.
Register list_invoices with your agent framework as a tool, or serve it from an MCP server. The tool description
the model sees says what it does ("List a customer's invoices") and nothing about keys.
The same pattern in a shell script, if your tool is a curl call. Passing the header on standard input keeps the key
out of the process list, where -H "Authorization: Bearer …" on the command line would show it to any user who runs
ps:
printf 'Authorization: Bearer %s\n' "$(age -d -i ~/.config/agent/identity.txt ~/.config/agent/secrets/billing-api-key.age)" \
| curl -sS -H @- "https://api.example.com/v1/invoices?customer=cus_123"
What should an MCP server's configuration hold?
Many MCP setups put the key straight into the client's configuration file:
{
"mcpServers": {
"billing": {
"command": "python3",
"args": ["billing_server.py"],
"env": { "BILLING_API_KEY": "sk_live_…" }
}
}
}
That file is plain text, gets copied between machines and shared in issues, and the key now sits in an environment variable of a long-running process. Point the server at the encrypted secret instead, and let its tool code decrypt it:
{
"mcpServers": {
"billing": {
"command": "python3",
"args": ["billing_server.py"],
"env": { "AGENT_IDENTITY": "/Users/you/.config/agent/identity.txt" }
}
}
}
The MCP specification itself splits by transport. For a local server over STDIO, implementations "SHOULD NOT follow this specification, and instead retrieve credentials from the environment"; for a remote server over HTTP it defines OAuth-based authorization, where "Access tokens MUST NOT be included in the URI query string" and the server accepts only tokens issued for itself, and passes none on (MCP authorization, 2026-07-28). The security best practices add that "token passthrough is explicitly forbidden": a remote MCP server must not take a client's token and pass it on to another API.
Can't the agent just read the key file itself?
If the agent has a shell tool or a file-reading tool running as the same user as your tool code, yes. Anything the
tool's code can read, a shell command can read too: cat ~/.config/agent/identity.txt, then age -d. Encrypting the
key at rest does not stop that. What stops it is a boundary the model's tools cannot cross:
- Run the credentialed tools where the agent's user cannot read, reached only through the tool interface: a
container, a service on another machine, or another operating-system user that owns the identity file
(
chmod 600), so the user the agent's shell runs as cannot open it. A separate MCP server running as the same user is not a boundary. - Do not give the agent a general shell on the machine that holds credentials. If it needs one, give it a sandbox without the secrets folder mounted.
This is the difference between hiding a key from the model's context and hiding it from the model's reach. The first stops accidental leaks through transcripts and output. Only the second stops a prompt-injected agent from fetching the key itself. It can still misuse the tool it was given, which is why the credential's scope matters next.
Which credential should the agent get?
Its own, and the smallest one that works:
- One credential per agent. When it is revoked, nothing else breaks, and logs show which agent did what.
- The narrowest scope the provider offers. A read-only key for an agent that only reads, restricted to the resources it needs. OWASP lists a "generic high-privileged identity" as a cause of excessive agency (LLM06:2025).
- Short-lived where possible. An OAuth access token that expires in an hour limits what a leak is worth.
- Its own encryption key pair. The agent's runtime is one more device. Its identity file encrypts nothing else, and revoking it does not touch your laptop's key.
What do you do after a key reaches the context anyway?
Treat it as exposed. Deleting the message does not delete transcripts, provider logs or anything the model already wrote elsewhere.
- Revoke the key at the provider and issue a new one.
- Store the new key encrypted, and give the agent the tool, not the value.
- Check the provider's logs for use you do not recognize, between the leak and the revocation.
- Delete local transcripts and settings files that contain it, and search your repositories for it.
Where does SecureSecretStore fit?
It is designed to be the store behind the _reveal function, for exactly this: an agent is a principal with its own age key
pair and a read-only API key scoped to named vaults; its code fetches the encrypted value and decrypts it locally, so
the value never passes through the store in the clear and never needs to enter the model's context. Its MCP tools
list names, metadata and the audit trail, never values. The service is not open yet; until then, the pattern above
works with files on disk.
Related reading: What an end-to-end encrypted secret store can and cannot see and Verify that an audit log was not edited.
For agents and tools: llms.txt. AI version of this article.