How to Give AI Agents API Keys Without Exposing Them
Published 2026-10-19 · Updated 2026-10-19 · By The Is My Agent Safe team
Short answer
Do not put provider keys in your shell profile or plaintext agent config. Create one narrowly scoped key per agent or MCP server, store it in OpenClaw's secrets store or a SecretRef, bind allowed hosts, and pass only that server's env. Set hard spend limits and rotate on a schedule. If a key already leaked, use the separate incident guide instead.
- One narrow key per agent or MCP server — never a personal account-wide token reused everywhere.
- Put values in the OpenClaw secrets store (or another SecretRef), not in shell exports or checked-in
.envfiles. - For local MCP: per-server env in the client config; nothing inherited from the parent shell.
- Cap spend at the provider, run
openclaw secrets audit --check, and point incidents at the leaked-key guide.
Agents need credentials to call model APIs, channels, and tools. The failure mode is simple: one broad key sitting in a shell profile, a plaintext config file, or a shared MCP process environment — then every skill, server, or prompt-injection path that can reach that process can reach the key.
This guide is prevention. If you already think a key leaked, stop here and follow Your AI agent's API keys may have leaked first.
Why "one key in the shell profile" fails for agents
MCP's local server security guide states the problem for local servers: a locally launched server may inherit the environment of whatever launched it. If your shell profile exports cloud credentials and API tokens globally, every server you run can potentially read all of them.
OpenClaw makes the same class of mistake expensive. Anything under ~/.openclaw/ may contain secrets or private data — including openclaw.json, credential files, and SQLite state — per the secrets, storage and logs docs. Workspace .env files often sit next to agent code and get committed by accident. OpenClaw blocks provider credential variables from untrusted workspace .env files, so a cloned workspace can't substitute an attacker's provider account.
The providers agree on the basics. OpenAI's API key best practices say to give each person their own key, set expiry dates with a rotation process, never ship keys in browsers or mobile apps, and set spend limits with hard enforcement. Anthropic's API key best practices say never to share keys, to use separate keys per use case and to rotate them on a schedule (for example every 90 days). Both prefer environment variables or a key management service over keys in code. An agent's environment is shared with everything it runs, so scope that environment per process too.
One narrowly scoped key per agent or MCP server
MCP's "Isolate Credentials" baseline:
- Pass secrets per server, not globally.
- Scope tokens narrowly — for example a fine-grained token limited to one repository, not an account-wide personal token.
- Do not reuse one personal broad-scope token across servers.
OWASP's MCP Security Cheat Sheet leads with the same principle of least privilege.
Practical pattern:
- Create a dedicated key (or bot token) for this agent or this MCP server only.
- Grant only the scopes that job needs.
- Prefer an expiry date where the provider allows it (OpenAI project keys and Anthropic keys both support one).
- Revoke that key when you retire the server — without touching every other integration.
Put secrets in a store or SecretRef, not plaintext config
Client configuration files are a known, predictable location on disk. MCP recommends an OS secret store where the client can reference it. OpenClaw's answer is the shared secrets store and SecretRefs.
Recommended operator loop from the secrets CLI. apply rewrites openclaw.json, auth profiles and .env files, is one-way for the plaintext values it scrubs, and keeps no rollback backups, so run the --dry-run line first, read what it will change, and only then run the real apply:
openclaw secrets audit --check openclaw secrets configure --plan-out /tmp/openclaw-secrets-plan.json openclaw secrets apply --from /tmp/openclaw-secrets-plan.json --dry-run openclaw secrets apply --from /tmp/openclaw-secrets-plan.json openclaw secrets audit --check openclaw secrets reload
Set a secret without putting it on the command line. For kind secret, --value is refused:
# pipe (stdin is not a TTY) op read 'op://Engineering/OpenAI/apiKey' | \ openclaw secrets store set OPENAI_API_KEY --kind secret # or interactive no-echo prompt openclaw secrets store set OPENAI_API_KEY --kind secret # or a regular file openclaw secrets store set TLS_PRIVATE_KEY \ --kind secret \ --value-file ./client-key.pem
--value is accepted only when the resolved kind is env (for example LOG_LEVEL). Names must match ^[A-Z][A-Z0-9_]{0,127}$.
OpenClaw blocks secret egress substitution until each secret has at least one exact allowed host. Bind them like this:
openclaw secrets store set OPENAI_API_KEY --allow-host api.openai.com
Hosts are policy metadata (shown in store list), not secret material. Schemes, paths, ports, and wildcards are rejected. The command binds or replaces a secret's host list, so pass --allow-host once for every host the key needs in the same command, then check the result with openclaw secrets store list.
Harden the host side too: ~/.openclaw at 700, openclaw.json at 600, full-disk encryption on the Gateway host, and a dedicated OS user when the host is shared — all from OpenClaw's secrets-and-storage guidance. openclaw doctor can warn and offer to tighten permissions.
OpenClaw: secrets store, audit, allow-host
Day-to-day commands worth muscle memory:
openclaw secrets store list openclaw secrets store set OPENAI_API_KEY --kind secret openclaw secrets store set OPENAI_API_KEY --allow-host api.openai.com openclaw secrets audit --check openclaw secrets reload
store get refuses secret entries (write-only by design), and secret values never appear in store list output. By default, secret entries stay out of subprocesses. Removing a name soft-deletes it and purges after 30 days.
secrets audit --check is the gate you can put in a weekly routine: plaintext findings, unresolved refs, shadowed refs, store residue, and legacy residues. Exit 1 on findings; unresolved refs return 2.
The Control UI (Settings → Secrets) and the agent's secrets tool also write to the store. The tool asks for the credential in a masked prompt, so the value doesn't reach the model. Never paste a key into the chat itself. OpenClaw's session transcripts keep pasted text, including keys, so if you already have, treat that key as exposed and replace it: Your AI agent's API keys may have leaked.
MCP local servers: per-server env, not inherited shell env
When a local MCP server needs a token:
- Put the token in that server's per-server environment in the client config — not in your login shell exports.
- Give that server only the token it needs.
- Prefer isolation (container with no home-directory mounts) so
~/.sshand cloud credential files are not readable even if the process misbehaves. - On OpenClaw,
openclaw mcp doctorflags literal sensitive header/env values in saved definitions — a sign to move those values into the secrets store or a SecretRef instead of plaintext. If that config was ever committed, shared or backed up somewhere others can read, rotate the key as well.
For how to decide whether to connect a server at all, see How to check an MCP server before you connect it.
Spend limits and rotation habits (prevention, not breach response)
Prevention includes making a leak less expensive before one happens:
- OpenAI: set a monthly spend limit for the organization or project and turn on hard enforcement. Alerts alone do not stop traffic.
- Anthropic: organizations on custom rate limits can set usage and spend limits. On standard rate limits, set auto-reload thresholds with care, because they decide how much credit refills.
- Rotate on a schedule and whenever someone who had access leaves, not only after an incident.
- Re-run
openclaw secrets audit --checkafter config changes and as part of a weekly pass (see weekly OpenClaw security checks for clients if you run installs for others).
None of this promises keys cannot leak. It shrinks how many places they live and how much each one can do.
If a key already leaked
Stop the Gateway, revoke and replace keys at each provider, set hard spend limits, and hunt the exposure path. Full steps: Your AI agent's API keys may have leaked.
Where next
- OpenClaw: secrets CLI · secrets, storage and logs
- MCP: Isolate Credentials
- Providers: OpenAI API key best practices · Anthropic API key best practices
- Checklist: 12-point AI agent security checklist
- MCP pre-connect: Check an MCP server before you connect it
Frequently asked questions
Can I pass a secret with `openclaw secrets store set --value`?
Only for kind env. OpenClaw's secrets CLI refuses --value when the resolved kind is secret, because command-line arguments can leak through shell history and process listings. Use a pipe, --value-file, or the interactive no-echo prompt instead.
Do workspace `.env` files override Gateway provider keys?
No. OpenClaw's secrets-and-storage docs say provider credential environment variables, and any OPENCLAW_* key, are blocked from untrusted workspace .env files, so a cloned workspace can't swap in someone else's provider account. The trusted process environment, the global runtime dotenv, the config env block and an enabled login-shell import still apply. For secrets, prefer the secrets store.
What does `openclaw secrets audit --check` look for?
Plaintext secret storage, unresolved refs, precedence drift, store residue duplicated in openclaw.json, generated models.json residues, and legacy residues. Exit code 1 on findings; unresolved refs return 2.
Is this the same as the leaked-key guide?
No. That guide is incident response: stop the agent, revoke, replace, cap spend, find the leak. This guide is prevention: architecture and day-to-day configuration so keys are harder to expose in the first place.
Does the free check manage my vault?
No. Paste your openclaw security audit output and openclaw --version into /check, and it spots risky settings, such as API keys handed to skills, and known-vulnerable versions. It does not store, rotate or vault your keys, and it doesn't review MCP servers or skill code.
Sources
- OpenClaw docs: openclaw secrets (CLI)
- OpenClaw docs: secrets, storage and logs
- MCP docs: Local Server Security — Isolate Credentials
- OpenAI Help Center: API key best practices
- Claude docs: authentication (key expiry)
- Claude Help Center: API key best practices
- OWASP: MCP Security Cheat Sheet
Get the weekly plain-English agent security brief
Agents & AI Security, explained: one short email a week. Free. Unsubscribe any time.
We'll only use your email to send the newsletter. The newsletter is sent by beehiiv, which records opens and link clicks. Privacy policy.