Articles

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:

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:

Shell
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:

Python
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:

  1. 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.
  2. 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.
  3. 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 Authorization header in a 401 body; the model's result read error: HTTP 401: bad key Bearer [redacted]. Redaction only catches an exact echo, not an encoded one.
  4. Redirects are refused. Python's urllib copies request headers, Authorization included, to wherever a redirect points. We measured it: a 302 to a second local server delivered the bearer token there. The _NoRedirect handler 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:

Shell
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:

JSON
{
  "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:

JSON
{
  "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:

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:

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.

  1. Revoke the key at the provider and issue a new one.
  2. Store the new key encrypted, and give the agent the tool, not the value.
  3. Check the provider's logs for use you do not recognize, between the leak and the revocation.
  4. 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.