Guide

AI Agent Security: Keep Your API Keys Secret and Defend Against Prompt Injection

AI agent security for builders: find leaked API keys, keep secrets out of the model's reach, vet MCP servers, and block prompt injection exfiltration.

· 15 min read

Agent security has become the loudest worry in the builder conversations we track, and the posts are specific. “AI agents are leaking credentials,” one began, citing GitGuardian’s count of secrets in public MCP config files (post). Another described what happens after a coding session goes wrong: “Your agent pasted your API key into the code and pushed it… deleting the line doesn’t fix it, cuz Git keeps every save point” (post). A third covered the attack side: an agent working in your signed-in browser is “a security problem waiting to happen. One poisoned web page and prompt injection does the rest” (post).

Those are two problems that make each other worse. Leaked secrets are the prize, and prompt injection is one way to grab them. This guide covers both: how to keep keys away from the model, and how to stop injected text from moving data out.

Scope: This guide covers secrets handling and injection defense. For tool permissions, allow/ask/deny tiers, human approvals, the “lethal trifecta,” and card spending limits, see our AI agent guardrails and permissions guide. The two guides are meant to be used together.

Why agents leak secrets

Keys sit where the model can read them

Most setups put API keys in a .env file, a shell profile, or an MCP config, all of which the agent can usually read. OWASP’s guidance for coding agents tells you to “assume anything in the agent’s process environment, shell history, or .env files can be read and sent out by an injected instruction” (OWASP AI Agent and MCP Security).

Agents also use whatever keys they find. One builder “caught an agent delegating to a better model since it had an openrouter key in the env” (post).

Config files get committed

GitGuardian’s 2026 report found “24,008 unique secrets exposed in MCP-related configuration files across public GitHub, including 2,117 unique valid credentials.” It also says part of the cause is documentation: “popular MCP setup guides often recommend putting API keys directly into configuration files, command-line arguments, or embedded connection strings” (GitGuardian, State of Secrets Sprawl 2026). The report’s top leaked types in MCP configs are Google API keys, PostgreSQL connection strings, and Firecrawl, Perplexity, and Brave Search keys (report page).

The same report found that Claude Code-assisted commits leaked secrets at 3.2%, compared with a 1.5% baseline for all public commits. GitGuardian adds that this “should not be read as a simple tool failure,” because people still decide what gets pushed.

Logs, traces and transcripts keep copies

Anything that passes through the context window can end up stored somewhere else. An October 2026 advisory for PydanticAI is a good example. Its OpenTelemetry instrumentation, even with include_content=False, could export retry prompts and “disclose validation feedback, including invalid model values quoted by that feedback, to readers of the telemetry backend.” The bug is fixed in versions 1.107.4 and 2.27.1 (CVE-2026-107293).

Local agent history counts too. One builder warned that every .env a coding agent printed, and every key pasted “just to test,” can be “sitting in plaintext logs” in the agent’s local folders (post). Another put it more bluntly: “Your AI coding agent keeps a plain-text copy of every API key you’ve ever pasted into it,” naming Claude Code, Codex, Gemini CLI, Cursor, and Cline as tools that save full sessions to disk (post). Backups multiply the problem. After a reported breach at OpenCode, one builder scanned their Mac and found “1 API token, 7 copies. Claude Code’s auto-backups cloned it for me” (post). Where those files live depends on the tool, so check your agent’s docs.

Why prompt injection makes leaks worse

OWASP defines indirect prompt injection as what happens when a model “accepts input from external sources, such as websites or files” and that content changes its behavior. It’s blunt about the fix: “it is unclear if there are fool-proof methods of prevention for prompt injection” (OWASP LLM01:2025).

The text doesn’t have to come from a web page. Invariant Labs showed a “tool poisoning” attack in which an MCP tool called add hid instructions in its description telling the model to read ~/.cursor/mcp.json and ~/.ssh/id_rsa and pass them along as a parameter. In their test with Cursor, the agent did it, and the confirmation dialog didn’t show the full arguments. They also describe “rug pulls,” where a server changes a tool’s description after you’ve approved it (Invariant Labs).

Security frameworks now treat this as a standard attack. MITRE ATT&CK v20, released Oct 13, 2026, added Direct Prompt Injection, Indirect Prompt Injection, and AI-Enabled Exfiltration as techniques. The last one describes attackers who “weaponize sanctioned tools available to the agent” to move data out (MITRE T1700).

Once an attacker controls the text, they need a way to get data out. Simon Willison lists the usual routes: outbound HTTP calls, links that carry data in the URL, and images, where “just the act of displaying this image would exfiltrate the user’s private data” (The Dual LLM pattern).

Why it’s dangerous to combine private data, untrusted content, and outbound access in one agent is covered in the guardrails guide’s lethal trifecta section. The steps below handle the two pieces it doesn’t: what secrets are within reach, and which exit routes are open.

Part 1: Handle secrets

Step 1: Find what’s already exposed

Before you change your setup, check what’s already out there:

  • Repos: check your full Git history, not just the current files, for keys, tokens, and connection strings. A secrets scanner does this faster than reading by hand.
  • MCP configs: open every MCP config file your clients use and look for literal keys in env, args, headers, or connection URLs.
  • Agent folders: search your agent’s local history and session folders for key prefixes you use (for example, sk-). Count the copies, not just the files: session logs and auto-backups can hold the same key several times.
  • Chat and tickets: GitGuardian found that about 28% of incidents start entirely outside code repositories, in tools like Slack, Jira, and Confluence.

Then turn on prevention. GitHub’s push protection for users “is enabled by default” and “stops you from pushing secrets to public repositories.” Repository-level push protection is off by default and has to be turned on by an admin (GitHub push protection).

Step 2: If a key leaked, revoke it first

Deleting the line or the commit doesn’t help, because the key is still in Git history, forks, and any copies already made. Revoke or rotate the key at the provider, then clean up. OpenAI’s guidance is: “If you believe your key has been leaked, rotate your key immediately,” then review usage to see whether it matches your own work (OpenAI API key safety).

Don’t put this off. GitGuardian retested valid secrets found in 2022 and found that 64% were “still active and exploitable” four years later.

In order:

  1. Revoke or rotate the key at the provider.
  2. Update the apps that legitimately use it.
  3. Check usage and billing for activity you don’t recognize.
  4. Remove the key from the code and history, and fix the setup that leaked it (Steps 3 and 4).

If a key already leaked, follow what to do after an API key leak.

Step 3: Get keys out of config files

Put a reference to the key in your config, not the key itself. Many clients can expand environment variables in their config. In Claude Code’s .mcp.json, for example, ${VAR} expands from your environment and works in command, args, env, url, and headers (Claude Code MCP docs):

{
  "mcpServers": {
    "api-server": {
      "type": "http",
      "url": "https://api.example.com/mcp",
      "headers": { "Authorization": "Bearer ${API_KEY}" }
    }
  }
}

With that, you can commit the file without committing the key. Check your own client’s docs for its syntax. Our MCP troubleshooting guide covers how env blocks reach stdio servers. Add any config files that still hold real values to .gitignore.

This keeps keys out of Git. It does not keep them away from the agent, because an agent that can run shell commands can read environment variables. That’s the next step.

Step 4: Keep the key out of the model’s reach

The goal is a setup where the agent can use a service without ever seeing its credential. There are three common patterns, from simplest to most involved:

  1. The tool holds the key. For tools you write, load the credential inside the tool code and return only the result. OWASP recommends giving the application “its own API tokens for extensible functionality” and handling those functions “in code rather than providing them to the model” (OWASP LLM01). OpenAI’s docs say the same for function tools: “keep credentials in the application that handles the call and return only the result” (OpenAI sandbox security).
  2. A proxy adds the key on the way out. For agents that run arbitrary code, the code uses a placeholder and “a network proxy supplies the real secret for approved hosts.” OpenAI warns that “injecting a stored secret into the environment still exposes it to agent-generated code.” Builders are shipping MCP gateways built on this idea. One describes Forgemax, an open-source MCP gateway, with the line “credentials stay on the host” (post). Another recommends a flow where the “agent never sees the token,” and adds: “Worth testing before trusting” (post). Commercial MCP gateways such as Speakeasy also check policy on each tool call. We haven’t tested these gateways. Treat them as options to evaluate, not recommendations.
  3. Block reads of secret files. If keys have to stay on disk, deny the agent read access to .env* and ~/.ssh/**. OWASP’s example policy does exactly this. Don’t assume the agent will steer clear on its own. One builder tested a one-letter typo fix with a fake key in .env: “claude read .env in its very first command.” It blanked the values with sed, and Codex saw the file but never opened it, so nothing leaked, but the read happened anyway (post). Set it up as a deny rule using the tiers in our guardrails guide.

Step 5: Make every key small and short-lived

Assume a key will leak eventually and limit what it can do when it does:

  • One key per agent and per tool. If one leaks, you revoke it without breaking everything else. OWASP also says to give agents “their own identity” rather than reusing your personal credentials.
  • Expiry dates. OpenAI lets you create project keys with an expiration date and recommends “a regular key rotation process.”
  • Hard usage caps on API keys. OpenAI notes that “spend alerts alone don’t stop API traffic,” so turn on hard enforcement where your provider offers it. If you route through OpenRouter, note that OpenRouter keys topped GitGuardian’s list of fastest-growing AI-service leaks in 2025 (48x, among detectors with more than 1,000 hits).
  • Narrow OAuth scopes. The guardrails guide covers scoping credentials, including MCP OAuth scopes.

If you build MCP servers yourself, the spec forbids “token passthrough”: servers “MUST NOT accept any tokens that were not explicitly issued for the MCP server” (MCP Security Best Practices).

Step 6: Keep secrets out of logs, traces and memory

  • Update your framework when an advisory like the PydanticAI one above comes out, and read what “redacted” actually covers.
  • Decide what traces store. Our production reliability guide covers the OpenAI Agents SDK’s trace_include_sensitive_data setting.
  • Never log secret values. OWASP says to send agent logs to a system “outside the agent’s control” and “avoid logging secret values.”
  • Never put secrets in memory. See our AI agent memory guide for what an agent should never store.

Part 2: Defend against prompt injection

Step 7: Map where untrusted text gets in

List every source of text your agent reads that someone else could write:

  • Web pages, including pages opened in a signed-in browser
  • Inbound email, texts, and chat messages
  • Documents, PDFs, and anything in a RAG index
  • Issues, pull request text, and dependency READMEs
  • MCP tool descriptions and tool responses
  • Instruction files such as AGENTS.md and rules files

OWASP’s guidance covers the last two specifically. It says to review instruction files “like code” and “scan for hidden Unicode characters” (OWASP AI Agent and MCP Security). Each item on this list is a place where an attacker can give your agent instructions.

Step 8: Vet and pin your MCP servers

An MCP server is code that runs next to your credentials, and its tool descriptions go straight into the model’s context. Claude Code’s docs say it plainly: “Verify you trust each server before connecting it. Servers that fetch external content can expose you to prompt injection risk.”

  • Check before you install. Look at the source repo, the maintainer, and the exact startup command the config will run.
  • Pin versions. OWASP says to pin an exact version or image digest “instead of npx some-server@latest.”
  • Re-review on change. OWASP warns that “a server can change its tool descriptions after you approved it,” so prefer clients that show or pin tool definitions.
  • Audit your “Always allow” answers. Each one removes a check an injected server could otherwise hit. One builder counted theirs: “There are 40 in one settings file. I had just read that one of those plus a bad MCP server let a prompt injection read private files. I am going through all 40 today” (post).
  • Watch project configs. Claude Code asks for approval before using servers from a project’s .mcp.json in interactive sessions. Its docs note that claude -p runs, Agent SDK sessions, and cloud sessions load them without asking.

Step 9: Close the exits

If injected text can’t send data anywhere, a successful injection does much less damage.

  • Allowlist outbound network access. OWASP calls this “the main control against data exfiltration after a successful injection.” Let the agent reach the domains its job needs and nothing else. MITRE’s mitigations for indirect prompt injection say the same: limit outbound communication for agents that process untrusted content (MITRE T1698).
  • Control links and images in output. Willison recommends allowing links only to “a previously approved allow-list of URL patterns,” and the same goes for images. OWASP’s LLM01 page includes this exact case: a summarized web page hides instructions that make the model insert an image linking to a URL, which leaks the private conversation.
  • Don’t let the agent fetch arbitrary URLs if it also has private data in context.

Step 10: Design so injected text can’t choose actions

You can’t train an agent to ignore every injection, but you can limit what injected text is able to change. A 2025 paper by researchers from ETH Zurich, Google, Microsoft, IBM and others states the principle: “once an LLM agent has ingested untrusted input, it must be constrained so that it is impossible for that input to trigger any consequential actions” (Design Patterns for Securing LLM Agents against Prompt Injections). Three of its patterns that solo builders can use:

  • Plan, then execute. The agent fixes its list of tool calls before it reads untrusted data. In the paper’s example, a request to send today’s schedule to your boss becomes calendar.read then email.write to a fixed address. An injection in the calendar “cannot inject any new instructions,” though it could still change the email’s body.
  • Map-reduce. Process each untrusted item with a separate, tool-less model call that returns a constrained value, such as true/false for “is this an invoice?” A malicious file can then only affect its own result.
  • Dual LLM. A privileged model plans and calls tools but never sees untrusted text. A quarantined model reads the text but has no tools. Willison, who proposed it, warns that the quarantined model’s output “should still be treated as potentially radioactive.”

Constrain output formats wherever you can. The paper recommends strict formats such as JSON with a fixed schema over free text, because free text is how injected instructions get passed along.

These patterns cost some capability. Google DeepMind’s CaMeL, a stronger version of this approach, solved 77% of tasks “with provable security” in the AgentDojo benchmark, compared with 84% for an undefended system (Defeating Prompt Injections by Design).

Step 11: Don’t rely on detectors; test with a canary

Prompt-injection classifiers and “guardrail” filters raise the bar, but the design-patterns paper calls them “fundamentally heuristic” with no guarantee. OWASP is direct: “Do not rely on the model to detect injections.” Researchers aren’t convinced it’s solved either. Florian Tramèr, promoting a $300,000 Gray Swan prompt-injection competition that runs until Nov 2, wrote: “AI labs often tell us that prompt injection is basically solved. Not convinced? (I’m not either…)” (post).

Test your setup yourself, using a test account:

  1. Plant a canary. Put a fake key (for example, sk-canary-1234) in the agent’s environment and in a decoy .env file.
  2. Inject. Put a hidden instruction in a test page, email, or document the agent will read, asking it to include that key in a link, an image, or a request to a URL you control.
  3. Check every exit. Look at your server logs, the agent’s output, its traces, and its local history for the canary string.
  4. Repeat after changes. Run it again whenever you add a tool, an MCP server, or a new input source.

The guardrails guide has a separate test list for permissions and spending. Run both.

Checklist

CheckDone when
Exposure scanGit history, MCP configs, agent folders, and chat tools checked for live keys
Leak responseLeaked keys revoked first, usage reviewed, history cleaned
Config filesOnly ${VAR}-style references in committed configs
Key isolationTools or a proxy hold credentials; agent can’t read .env or ~/.ssh
Key sizeOne key per agent and tool, with expiry and hard usage caps
Logs and tracesFramework patched, sensitive-data settings reviewed, no secrets in memory
Input mapEvery untrusted text source listed
MCP serversVetted, pinned, and re-reviewed when tools change
ExitsOutbound allowlist; links and images restricted
DesignUntrusted text can’t add tool calls
Canary testFake key never appears outside the agent

FAQ

Can prompt injection steal my API keys? Yes, if the agent can read the key and send data out. Keep keys in the tool or a proxy so the model never sees them, deny reads of secret files, and restrict outbound network access.

My AI agent pushed an API key to GitHub. What do I do? Revoke or rotate the key at the provider first. Deleting the commit isn’t enough, because the key stays in Git history and any copies. Then check usage for activity you don’t recognize, update your apps, and remove the key from history.

Is it safe to put API keys in an MCP config file? Not as literal values. GitGuardian found 24,008 secrets in public MCP-related config files. Use environment variable references, keep files with real values out of Git, and keep in mind that environment variables can still be read by an agent with shell access.

What is MCP tool poisoning? It’s a prompt injection hidden in an MCP tool’s description. The model sees the full description and may follow its instructions, such as reading key files. Vet servers, pin versions, and re-review tools when their definitions change.

Does my coding agent keep copies of my API keys? It can. Coding agents save sessions to disk, so a key you pasted or a .env file the agent read can sit in plain-text history and backups. Search those folders for your key prefixes, rotate anything you find, and deny the agent reads of secret files.

Do prompt injection detectors work? They catch some attacks but offer no guarantee. Use them as an extra layer, and rely on design: keep secrets out of reach, close outbound channels, and stop untrusted text from choosing actions.


Get the next guide in your inbox

We’re tracking secrets leaks, injection attacks, and the tools that claim to stop them, for people building AI agents and Grok Bot setups. Subscribe to the newsletter for practical guides and directory picks.