Join our Newsletter — 33% off our NHI Course
Home› Guides› Prompt Injection Guide: Direct, Indirect and Tool Poisoning
Guide AI Security

Prompt Injection Guide: Direct, Indirect and Tool Poisoning

← All guides
By Lalit Choda, NHI Mgmt Group Updated 16 October 2026 17 min read
On this page

A large language model cannot reliably tell the instructions it was given by its developer apart from instructions hidden in the text, images and tool data it reads, so anyone who can put content in front of the model can try to steer it. This guide goes deeper than the general agent guidance: it covers direct and indirect injection, hidden and multimodal carriers, tool description poisoning, the exfiltration channels attackers rely on, and where screening and hard controls belong. It is written for application security engineers, AI platform teams and security architects who build or approve LLM applications and agents. It describes techniques at the level defenders need and contains no working attack strings.

Key takeaways

  • Treat injection as a residual risk, not a bug to patch. The UK NCSC describes an LLM as an "inherently confusable deputy" and warns that prompt injection may never be fully mitigated; design so that a successful injection does limited harm.
  • Indirect injection is the enterprise problem. Direct injection comes from the person typing; indirect injection arrives in emails, web pages, documents, tickets, calendar invites and tool output that the user never reads closely.
  • Screen at every trust boundary, enforce at the tool boundary. Classifiers on input, retrieved content and output reduce attack volume, but the controls that hold are deterministic: permissions, egress rules and approval checks enforced in code outside the model.
  • Break the lethal trifecta. An agent that has private data, reads untrusted content and can communicate externally can be turned into an exfiltration tool; remove one leg for each workflow.
  • Tool descriptions are prompts too. MCP and plugin tool metadata is read by the model as instructions, so tool poisoning, silent description changes and cross-tool shadowing need pinning, review and monitoring like any other supply chain input.

What prompt injection is, and what it is not

OWASP's LLM01:2025 defines a prompt injection vulnerability as one that "occurs when user prompts alter the LLM's behavior or output in unintended ways"; the injected content only has to be parsed by the model, not read by a human. The NCSC explains why it differs from SQL injection: parameterised queries separate code from data, but inside an LLM "there is only ever 'next token'", so there is no equivalent parameter boundary to enforce.

VariantWhere the instruction comes fromTypical channelReference IDs
Direct prompt injectionThe user of the applicationChat box, API prompt fieldOWASP LLM01; MITRE ATLAS AML.T0051.000; NIST AI 100-2 NISTAML.018
Indirect prompt injectionA third party who controls content the model readsWeb pages, email, files, RAG documents, tool outputAML.T0051.001; NISTAML.015; OWASP Agentic ASI01 Agent Goal Hijack
Triggered injectionContent that activates on a later user action or system eventScheduled agent runs, stored records, memoryAML.T0051.002
JailbreakUsually the user, aiming to bypass safety trainingRole play, adversarial suffixes, obfuscationAML.T0054 LLM Jailbreak; OWASP calls jailbreaking "a form of prompt injection"
System prompt extractionUser or third partyRequests to repeat hidden instructionsAML.T0056; NISTAML.035 Prompt Extraction
  • Prompt injection vs jailbreak: a jailbreak targets the model provider's safety behaviour; prompt injection targets the application's intent. A perfectly "safe" model will still forward a document on an attacker's instruction, because forwarding is a legitimate capability.
  • Unintentional injection: OWASP includes cases with no attacker, such as a hidden instruction in a job advert triggered by a candidate's AI-written CV.
  • Second-order injection: the payload is stored first (a CRM record, a support ticket, an agent memory entry, a message from another agent) and executes when a different, more privileged workflow reads it later. OWASP's Agentic Top 10 lists this territory under ASI06 Memory and Context Poisoning and ASI07 Insecure Inter-Agent Communication.

Injection channels and hiding techniques

Attackers need a channel the application trusts and a way to keep humans from noticing. MITRE ATLAS groups the hiding methods under AML.T0068 LLM Prompt Obfuscation: tiny or background-coloured text, hidden HTML, instructions in image pixels or file metadata, and encodings such as base64 or ROT13.

Channel or carrierHow it reaches the modelDefensive check
Hidden text in documents and web pagesWhite or zero-size text, HTML comments, CSS-hidden elements survive text extractionExtract to plain text, drop hidden elements, flag documents whose extracted text differs sharply from rendered text
Invisible Unicode (tag block U+E0000 to U+E007F, zero-width characters)Characters render as nothing but are read by the modelStrip tag-block and other invisible code points before inference; AWS recommends repeating sanitisation until the text stops changing, because one pass can create new tag characters from surrogate pairs
Images, audio and scans (multimodal and typographic attacks)Text inside an image or audio is transcribed or read directly by a multimodal modelTreat OCR and transcription output as untrusted content with the same provenance label as its source
File metadata and commentsDocument properties, EXIF, code comments, commit messagesExclude metadata from context unless the task needs it
Retrieved content (RAG)Planted documents in indexed shares, wikis or tickets (ATLAS AML.T0071 False RAG Entry Injection)Control who can write to indexed sources; record source and author per chunk. See the Permission-Aware RAG Guide.
Inbound business recordsWeb forms, emails, calendar invites, CRM leads processed by an agentProcess with a tool-less model or deterministic parser before any privileged agent sees them
Tool and MCP server metadataTool names, descriptions and parameter schemas are placed in the model's contextReview, pin and hash tool definitions; alert on changes
Tool output and other agentsAPI responses, error messages, sub-agent repliesLabel as untrusted; never let output change the plan without a policy check
Encoded or split payloadsBase64, other languages, emoji, payload split across fields that combine laterDecode for inspection; do not rely on keyword filters

Tool description poisoning

Invariant Labs described three related attacks on Model Context Protocol (MCP) clients in April 2025. In tool poisoning, a malicious server ships a tool whose description contains instructions for the model, while the client shows the user only a short name. In a rug pull, a server the user already approved changes its tool descriptions later. In shadowing, one server's description changes how the agent uses a different, trusted server's tool, without the malicious tool ever being called. The defences are supply chain defences: show full descriptions, pin versions, hash descriptions and re-approve on change, and restrict data flows between servers. See the MCP Security Guide. The postmark-mcp malicious server showed how little code a hostile MCP server needs to copy every email an agent sends.

What a successful injection achieves

Impact depends on what the application can do, not on how clever the injected text is.

  • Exfiltration through rendering: the model is induced to output a markdown image or link whose URL carries data; the client fetches it automatically. ATLAS tracks this as AML.T0077 LLM Response Rendering. Microsoft reports that it deterministically blocked markdown image exfiltration in its products after a researcher report, and then the wider class of untrusted link generation.
  • Exfiltration through tools: the agent sends data using a tool it legitimately holds, such as email, HTTP fetch, ticket creation or a code commit (ATLAS AML.T0053 AI Agent Tool Invocation, OWASP ASI02 Tool Misuse and Exploitation).
  • Zero-click compromise: no user action is needed beyond normal use. EchoLeak (CVE-2025-32711, CVSS 9.3 from Microsoft as CNA) let a crafted email make Microsoft 365 Copilot disclose organisational data, and SalesBleed used poisoned Web-to-Lead records to turn Agentforce agents into data thieves.
  • Action hijack: the agent changes records, approves requests, sends phishing on the organisation's behalf or runs code. OWASP Agentic ASI01 calls this goal hijack.
  • Persistence and spread: instructions written into memory or other agents' inputs outlive the original content (AML.T0061 LLM Prompt Self-Replication).

Simon Willison's "lethal trifecta" is the most useful risk test: access to private data, exposure to untrusted content and the ability to externally communicate. Where all three are present in one agent context, assume a determined attacker can extract the data. See the Agentic AI Security Guide for the broader agent threat model.

Where to screen content, and what screening cannot do

Content screening works best when it sits at each point where trust changes, and it is never the last line. The OWASP prevention cheat sheet is explicit that labels and delimiters are "not an enforcement boundary" and that enforcement belongs at the tool boundary; Microsoft describes detection of indirect injection as "still an open research challenge".

LayerControlTypeStopsLimits
1. User inputInjection and jailbreak classifier, length and rate limitsProbabilisticDirect injection, Best-of-N retriesBlind to indirect content
2. Ingestion and retrievalNormalise and strip invisible characters, drop hidden elements, classify each document or chunk before it enters context, tag provenanceMixedMost hidden and indirect carriersParaphrased or novel injections pass
3. Prompt assemblyInstruction hierarchy, spotlighting, hardened system promptProbabilisticReduces model compliance with embedded instructionsCan be overridden; never a security boundary
4. Tool callPolicy check of every proposed call against user, data and destination; parameter validation; human approval for high-impact actionsDeterministicUnauthorised actions and tool exfiltrationApproval fatigue if overused
5. OutputBlock or rewrite external URLs and images, scan for secrets and system prompt fragments, validate output format in codeMostly deterministicRendering exfiltration, leakageNeeds a maintained allowlist of domains
6. MonitoringLog prompts, retrieved sources, tool calls and denials; alert on anomaliesDetectiveFinds what slipped throughOnly as good as retention and review
  • Answer to "where should screening take place": on retrieved and tool-returned content before it enters the context (layer 2), and on proposed actions before they execute (layer 4). Screening user input alone misses the indirect attacks that cause most enterprise impact.
  • Classifier numbers: Willison calls 95% detection "very much a failing grade" for a security control, because an attacker only needs the 5%. The OWASP cheat sheet adds that guardrail models can themselves be injected.
  • Deny-lists: the NCSC advises against them; attackers rephrase, translate, encode or scramble letters (typoglycemia) around keyword lists.

Architectural patterns that limit the blast radius

Model-level defences lower the odds; architecture limits the damage. A 2025 paper by researchers from IBM, Invariant Labs, ETH Zurich, Google, Microsoft and others sets the principle: once an agent has ingested untrusted input, it "must be constrained so that it is impossible for that input to trigger any consequential actions".

PatternHow it worksUse whenTrade-off
Instruction hierarchy (model training)Model is trained to prefer system over user over tool-supplied instructions (OpenAI, 2024)Always, as a baselineProbabilistic; depends on the model provider
Spotlighting (delimiting, datamarking, encoding)Untrusted text is wrapped, marked token by token or encoded so the model can tell its source (Microsoft, 2024)Summarising or answering over external contentPaper reports attack success falling from above 50% to below 2%; still not a boundary
Action-SelectorModel only maps a request to predefined actions; tool output never returns to itCustomer service bots, command routersLittle flexibility
Plan-Then-ExecutePlan is fixed before untrusted data is readWorkflows with predictable stepsInjected data can still alter parameters of planned steps
Dual LLM / CaMeLA privileged model plans and calls tools but never sees untrusted text; a quarantined model with no tools processes it and returns references, not contentEmail, browsing and document agents with sensitive toolsEngineering effort; Willison, who proposed Dual LLM, notes the user experience cost
LLM Map-ReduceEach untrusted item is processed by an isolated model; outputs are constrained before aggregationBulk triage of CVs, tickets, reviewsOutputs must be tightly typed
Code-Then-ExecuteModel writes a program before seeing data; program runs over dataAnalytical agentsRequires a sandbox
Context-MinimisationRemove content from context once it has served its purposeMulti-turn assistantsLoses conversational memory

Choosing controls for your application

  • Chatbot with no tools and no private data: the main risks are reputational and contractual, as the Chevrolet dealer chatbot and DPD chatbot incidents showed. Input classifiers, a constrained system prompt, output validation and clear statements that the bot cannot make offers are proportionate.
  • RAG assistant over internal data: retrieval must respect the requesting user's permissions, indexed sources must have controlled write access, and output must not render external images or links. Without external communication, the trifecta is broken.
  • Agent that reads inbound content and holds sensitive tools: email, CRM, browsing and ticketing agents need Dual LLM or Plan-Then-Execute separation, egress allowlists and approval for sends, shares and payments. The ForcedLeak case combined an inbound web form with an expired domain that had stayed on a trusted list.
  • Coding agents: repositories, issues, READMEs and error reports are untrusted input. Run agents in sandboxes without production credentials and require approval for shell commands that touch the network. See the AI Coding Agents Security Guide.
  • Small organisations: mostly consume copilots and SaaS agents, so focus on configuration: restrict connectors, limit agent data scopes, and ask vendors how they handle indirect injection and markdown exfiltration.
  • Large organisations building agents: provide a shared gateway that performs layer 2, 4 and 5 controls once for all product teams.

Implementing defences in phases

  1. Inventory: list every LLM feature and agent, the data it reads, the tools it calls and every channel carrying third-party content into it. Mark each against the lethal trifecta.
  2. Cut privileges first: give each agent its own identity and scoped credentials, read-only where possible, and remove tools no workflow needs. This is cheap, deterministic and immediately reduces impact.
  3. Close exfiltration paths: block automatic rendering of external images and links in model output, and set egress allowlists for agent HTTP tools.
  4. Add ingestion hygiene: normalise Unicode, strip invisible characters and hidden markup, label provenance, and run an injection classifier on retrieved and inbound content. Start in log-only mode to measure false positives on real traffic.
  5. Add tool-call policy: evaluate each proposed call in code against the user's entitlements, data sensitivity and destination. Run in audit mode for two to four weeks, review denials, then enforce for a pilot group before general rollout.
  6. Introduce human approval for irreversible or external actions, showing the exact action and parameters, not a summary written by the model.
  7. Test adversarially: build a regression suite covering direct, indirect, hidden, multimodal and tool-description cases; rerun on every model, prompt or tool change, and repeat each case several times because outputs vary. See Red Teaming AI Agents for Identity Abuse.
  8. Plan rollback: keep a kill switch per agent and per tool, version system prompts and tool definitions in configuration management, and be able to revoke the agent's credentials in minutes.

Detection and measurement

The NCSC recommends logging model inputs and outputs, tool use and API calls, and notes that failed tool calls may reveal an attack early.

  • Log: user prompt, retrieved document IDs and sources, classifier verdicts, the full proposed tool call with parameters, policy decision, approver, and output URLs.
  • Alert on: tool calls denied by policy, a read of sensitive data followed by an external send in the same session (OWASP ASI02 calls out this chaining), outbound requests to new domains, invisible Unicode in inbound content, and changes to tool or MCP server definitions.
  • Integrate with the SOC: route AI alerts (for example Prompt Shields detections in Defender XDR) to the same incident queue. See the AI Agent Observability and Incident Response Guide.

Metrics that show the programme is working:

  • Attack success rate on your regression suite per model and release, reported with the number of runs, as the OWASP cheat sheet recommends.
  • False positive rate of input and ingestion classifiers on benign traffic.
  • Trifecta exposure: percentage of agents that combine private data, untrusted input and external communication without a compensating control.
  • Policy-blocked tool calls per thousand sessions, with time to triage.
  • Tool definition drift: unapproved changes to pinned MCP or plugin definitions detected.

Where identity fits

Microsoft's MSRC notes that indirect prompt injection relies on the application "operating with the same level of access permissions as the user". The NCSC, aligning with ETSI TS 104 223, puts it the other way round: a model processing a party's content should not hold more privilege than that party. Identity controls are therefore the most reliable limit on impact.

  • Separate agent identities: give each agent and tool connection its own non-human identity, so actions are attributable and revocable. See the Agentic AI Identity Guide.
  • Per-action authorisation: check the requesting user's rights at the moment of each tool call, rather than granting the agent a standing superset. See the AI Agent Authorisation Guide.
  • Short-lived, scoped tokens: an injected agent with a narrow, expiring token does far less damage than one with a long-lived API key. See the API Key Management Guide.

Framework mapping

FrameworkEntryRelevance
OWASP Top 10 for LLM Applications 2025LLM01:2025 Prompt InjectionDefinition, seven mitigation strategies, attack scenarios
OWASP Top 10 for Agentic Applications 2026ASI01 Agent Goal Hijack; ASI02 Tool Misuse and Exploitation; ASI06 Memory and Context PoisoningInjection as the route to goal change, tool abuse and persistent poisoning
MITRE ATLASAML.T0051 (.000 Direct, .001 Indirect, .002 Triggered); AML.T0054; AML.T0068; AML.T0056; AML.T0057; AML.T0053; AML.T0077Technique IDs for threat models, detections and incident reports
NIST AI 100-2 E2025Sections 3.3 Direct Prompting Attacks and 3.4 Indirect Prompt Injection; NISTAML.018, NISTAML.015, NISTAML.035Common terminology for availability, integrity, privacy and misuse goals
CWECWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream ComponentWeakness class assigned to EchoLeak (CVE-2025-32711)

Common failure patterns

  • Relying on the system prompt as a control. Instructions such as "never reveal data" are probabilistic. The Gemini calendar injection showed a single malicious invite overriding an assistant's intended behaviour.
  • Screening the chat box but not the content. Most enterprise incidents arrive indirectly: email in EchoLeak, a web form in ForcedLeak, CRM leads in SalesBleed.
  • Treating developer content as trusted. READMEs, issues and error reports are attacker-writable. The Gemini CLI flaw used a poisoned README, and Sentry MCP agentjacking used a fake error report to hijack coding agents.
  • Approving MCP servers once and never again. Rug pulls change descriptions after approval; without pinning and change alerts nobody notices.
  • Leaving rendering and egress open. Output that can load arbitrary images or call arbitrary URLs turns any injection into data loss.
  • Over-privileged agent credentials. An agent holding an administrator token turns every injection into an administrator compromise.

Practitioner checklist

  • Inventory LLM features and agents with their data, tools and untrusted input channels, and flag every lethal trifecta.
  • Give each agent its own scoped, short-lived credentials and remove unused tools.
  • Block automatic rendering of external images and links in model output and allowlist agent egress.
  • Normalise Unicode, strip invisible characters and hidden markup, and screen retrieved and tool-returned content before it enters context.
  • Enforce a code-level policy check on every tool call, with human approval for irreversible or external actions.
  • Pin, hash and review MCP and plugin tool definitions, and alert on changes.
  • Separate untrusted content processing from privileged planning (Dual LLM, CaMeL or Plan-Then-Execute) for high-risk agents.
  • Maintain an injection regression suite and rerun it on every model, prompt or tool change.
  • Log prompts, sources, tool calls and policy denials into the SOC, with a kill switch per agent.

Standards and references

Related NHI Mgmt Group resources: Agentic AI Security Guide · MCP Security Guide · Enterprise AI Copilot Security Guide · Permission-Aware RAG Guide · Red Teaming AI Agents for Identity Abuse

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Written and reviewed by Lalit Choda, NHI Mgmt Group. Last updated 16 October 2026.
NHI Mgmt Group — the #1 independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org