Prompt Injection Defense for AI Agents and MCP Tools: Layers, Tools and Testing
Defending AI agents and MCP tools against prompt injection requires layered controls, a combination of red teaming and runtime blocking, and ongoing testing in production. AI agents are gaining momentum from experimental copilots to systems capable of reading emails and querying databases and internal systems without human input. This autonomy is what makes prompt injection dangerous: a manipulated prompt can lead an agent to send data out, edit a record or trigger a payment API rather than simply say the wrong thing. Prompt injection defense is now a board-level issue, as AI agents are embedded in real workflows connected via MCP servers and third-party tools that add to the attack surface with each new integration. This article covers why traditional filtering is ineffective, the order of defense layers, the threats to consider, and the shape of production-ready AI agent security.
Which tools detect and block prompt injection attacks on AI agents in production?
Tools to evaluate for detecting and blocking prompt injection on AI agents include Akto, Lakera Guard, Datadog AI Guard, Azure Prompt Shields, Amazon Bedrock Guardrails and NVIDIA NeMo Guardrails. The right choice depends on where an agent reads untrusted content, which tools it can call and where a security decision can be enforced. For agents connected to internal systems or MCP servers, evaluate coverage for retrieved documents, tool arguments and tool results beyond the first user prompt, confirm that a blocking decision stops the relevant request before execution, and test that legitimate work still completes. For a wider comparison of runtime controls, see runtime AI guardrails.
Why prompt injection is a critical enterprise risk
Prompt injection became more than a theoretical risk of language models the moment enterprises began entrusting AI systems with the ability to take action rather than just respond. When an agent can call a tool, touch a database, or send a message on somebody's behalf, a manipulated prompt becomes an operational security incident rather than an embarrassing output.
Why AI agents are different from chatbots
A chatbot creates text, while an AI agent plans, decides and executes: it can hold credentials, make calls to APIs, link several steps together, and frequently persist memory from one session to another. Agentic AI reasons about a desired objective and executes it autonomously, using tools as necessary with only limited human oversight of each step, and an attacker uses that agency to their advantage. A successful injection into a chatbot generates a bad sentence; a single successful injection into an agent can result in a bad action, which is why AI Agent Security needs to address execution, not just generation.
Why traditional prompt filtering is no longer enough
Most initial defenses were designed to block a much more basic attack model: a denylist of bad phrases, a regular expression for known jailbreak strings, or a classifier trained on a few examples of attacks. These approaches only work for pre-known attacks; they fail against paraphrased or encoded tricks, input in another language, or instructions hidden within a document or a tool's answer rather than entered by a user. Static filtering also has no visibility into what happens after a prompt is accepted; it cannot know that an agent will call a tool it hasn't called before, or pass data to an unusual destination. Real defense must go beyond the input box and apply during execution.
Why traditional defenses fail for agentic AI
Not all prompt injection looks alike to older controls. Some comes from a user, and some comes from an indirect source, hiding inside content the agent had no reason to distrust.
Direct vs. indirect prompt injection
Direct prompt injection occurs when an attacker types an instruction directly into the chat window or API call to bypass the system prompt or have the model disregard its instructions; it is the most obvious type of AI agent prompt injection, and the type most current filters are designed to detect. Indirect prompt injection is different: the attack is inserted into a web page, PDF, email message, support ticket, or data returned from a tool the agent uses, and is retrieved as part of its work without an attacker being involved in the conversation. The same result can be achieved via either path, but indirect injection is the one enterprises are least prepared for, because it doesn't appear like an attack at the point of entry.
Why indirect prompt injection is harder to detect
Indirect injection is difficult to detect because the malicious text is embedded in normal text the agent was already expected to handle. A hidden instruction in a product review, calendar invite, or API response can tell the agent to exfiltrate data or call a different tool, and the surrounding text doesn't look suspicious to a keyword filter. This is a form of context manipulation: the attacker does not attack the model directly, but modifies the information the agent relies on, and the model follows that context as valid, ending up on a path toward a dangerous action.
The unique threat of MCP tool poisoning
The Model Context Protocol has made it much easier to connect agents to external tools, bringing a new risk: MCP Tool Poisoning. When an agent evaluates which tool to call, it may read and follow hidden instructions in the description or metadata field of a tool published by a malicious or compromised MCP server with a legitimate-looking name. This is a dangerous gap in current MCP Security practice, because tool descriptions are treated as trusted configuration rather than untrusted input, something most application-layer defenses were never designed to examine.
Multi-step and multi-turn attack chains
A realistic attack sets an instruction in an early part of a session, lets it remain in memory or context, and waits until a later step or turn to cause the harmful action, which the agent will often have already granted permission for at a previous step. Each tool call in the sequence can seem innocuous when taken individually; only when seen together does it show an attacker walking the agent toward data exposure or an action it was never meant to take.
A layered framework for prompt injection defense
Prompt injection is not defeated by a single control; a multi-layered approach is needed to prevent it. The three layers below cover the complete life cycle of a request: before it reaches the model, through the life of the agent acting on the request, and before the response leaves the system.
Layer 1: Input guardrails and detection before execution
The first layer operates on all inputs to the system, from a user, a document, or connected tools.
- Input Validation
- Ensuring incoming data is in the correct format, length and type before it is passed to the model, rather than letting it reach downstream boundaries without being recognized as incorrect or too large.
- Prompt Injection Detection
- Flagging instructions that try to change system behavior through prompt injection, as opposed to generic content moderation, using classifiers and pattern analysis trained specifically for prompt injection detection.
- Prompt Shielding
- Enclosing untrusted content, such as documents retrieved from the internet or the output of a tool, in a way that makes it clearly identifiable as separate from trusted content, so the model treats it as data to consider rather than instructions to follow.
- Input Classification
- Classifying inputs by source and trust level (user-provided, retrieved, tool-returned), so lower-trust inputs are automatically subjected to a higher level of scrutiny.
Layer 2: Runtime protection for AI agents
The second layer monitors the agent as it works, since this is where intent becomes action.
- Runtime Tool Call Validation
- Validating that every call is made with valid parameters, valid tools and valid task context at runtime, to catch calls inconsistent with what the agent should be doing at that step.
- Behavioral Monitoring
- Setting a baseline of how an agent normally operates and flagging a change, such as an unusual sequence of tool calls or a sudden increase in data volume accessed.
- Least-Privilege Tool Access
- Minimizing the access agents have to tools and data, so that even if an injection succeeds, the resulting damage radius is small rather than large.
- Runtime Blocking and Enforcement
- The ability to actively prevent suspicious activity in real time, instead of just recording it, the difference between an alert no one sees in time and an attack that never takes place.
Layer 3: Output guardrails and response validation
The third layer verifies the information the agent intends to send back to the user or to another system.
- Output Filtering
- Checking the model's responses for evidence that an injected instruction succeeded, such as leaked system prompts or unexpected formatting indicating that the model executed a hidden command.
- PII Redaction
- Detecting and redacting supported sensitive-data types under configured policies, combined with tool permissions and destination restrictions to control how data is used and shared.
- Schema Validation
- Validating structured outputs, such as API payloads or function call arguments, against the corresponding schema before downstream execution.
- Output Sanitization
- Removing or sanitizing any executable content, markup or embedded instructions from a response before displaying or sending it to another agent or tool.
For configuration examples, see LiteLLM PII protection. For broader data-handling controls, read GenAI data loss prevention; redaction should be paired with permissions that define which tools and destinations an agent may use. To understand how retrieved data can redirect an agent, read indirect prompt injection through tool output.
Detection vs. blocking: why runtime enforcement matters
Not every AI security solution is built to do the same thing, and the distinction between detection and prevention matters most in production.
Detection-only tools
A detector evaluates content as a request arrives and returns a score, flag or policy verdict. The application, gateway or integration then decides what happens next. In monitor mode, findings are logged for review while the request continues.
Runtime blocking platforms
Inline enforcement puts the policy decision in the request path. A check before a model request or tool call can stop that request before it is dispatched. Screening a tool result can keep malicious instructions out of the next model step, but it cannot undo an action the tool has already completed.
Why enterprises need both visibility and enforcement
Security teams need a record of what agents do and a way to act on policy violations. Logs help investigate incidents and tune policies, while inline runtime guardrails apply those policies as requests move through the workflow.
What's the difference between red teaming before deployment and runtime prevention after deployment?
Red teaming and runtime prevention both defend against prompt injection, but at different times and against different failures: red teaming finds weaknesses before an attacker does, while runtime prevention stops the attacks that get through anyway, and neither replaces the other.
| Aspect | Red teaming before deployment | Runtime prevention after deployment |
|---|---|---|
| When it runs | In CI/CD, before release and on a schedule in staging | On every live prompt, retrieved document, tool call and tool result |
| What it uses | Simulated attacks against test agents, with synthetic data | Real production traffic |
| What it delivers | Findings to fix before attackers find them | Blocked requests and tool calls, as they happen |
| What it covers | The attack techniques in its test suite, including new variants it generates | Any input, including attacks no one has seen before, if a policy catches it |
| Blind spot | Attacks missing from the suite, and conditions that only exist in production | Can't reveal a weakness until an attack hits it, and needs tuning to avoid false positives |
| How you prove it works | A finding, or a failed release gate, before deployment | A blocked action with zero downstream executions in the logs |
The two work best as one loop: testing feeds runtime, as every confirmed red team finding becomes a runtime policy, and runtime feeds testing, as every attack that runtime blocks becomes a new test case. Red teaming without runtime protection leaves production exposed between test runs; runtime protection without red teaming leaves a team guessing whether its policies hold up against current techniques. When evaluating a platform, ask the vendor to show each separately: a red team finding from your own agent, and a live tool call blocked before execution.
Which prompt injection tools should be compared for AI agents?
Start with the part of a workflow that needs protection, check whether a tool screens user messages, retrieved content, tool arguments or tool results, then identify which component blocks a policy violation.
| Tool | Production use | How enforcement works |
|---|---|---|
| Akto | Runtime protection for AI agent, gateway and MCP workflows. | Configured integrations apply guardrail decisions at model and tool interaction points. |
| Lakera Guard | Content and agent-interaction screening. | The Guard API returns findings; the application or gateway handles the response. |
| Datadog AI Guard | Protection and monitoring for supported agent workflows. | SDK blocking requires the appropriate configuration. HTTP API integrations must act on the returned decision. |
| Azure Prompt Shields | Detecting attacks in user prompts and documents. | Configured Foundry filtering can block. Standalone detection results need application handling. |
| Amazon Bedrock Guardrails | Prompt-attack filtering and content evaluation. | Select the API and content scope carefully. The prompt-attack filter does not automatically inspect tool definitions or tool results. |
| NVIDIA NeMo Guardrails | Programmable guardrails for application flows. | Configured input, retrieval, execution and output rails determine where checks and actions run. |
Each tool name links to its official documentation. Compare the current integration and policy settings, then test them against your own tasks and attack scenarios; monitoring, content classification and blocking serve different roles.
Prompt injection attack vectors every enterprise must defend against
The first step in building a defense program is having a plan of what it will defend against. The following vectors are the most frequently observed in real-world agent and MCP deployments.
- Direct Prompt Injection
- An attacker puts instructions in a user message to override the agent's task or system instructions. Common examples include fake system messages, role-play scenarios and requests to ignore earlier instructions.
- Indirect Prompt Injection
- Malicious instructions are inserted into external content that the agent processes as part of its regular task, such as a page it is summarizing or a document it is fetching, but that is not part of the conversation.
- MCP Tool Poisoning
- A tool with a correct name is published by a compromised or malicious MCP server with a description or metadata that contains instructions to alter the agent's behavior when the tool is evaluated or called.
- Rug Pull Attacks
- A tool or MCP server behaves safely during initial review or early use, but changes its behavior once trusted and integrated, returning instructions or actions it would not have shown during closer scrutiny.
- Jailbreaks
- An attempt to get the model to ignore its safety training or usage requirements altogether, usually involving elaborate framing, hypothetical scenarios, or a complex social engineering process rather than one simple command.
- Privilege Escalation
- An agent is tricked into accessing data, calling a tool, or performing an action outside the context of the task or role it is designed to perform, typically by proceeding through multiple steps over time rather than a single visible step.
- Prompt Leakage
- The attacker obtains the system prompt, internal instructions, or configuration details the agent was never designed to give out, which can then be leveraged into more targeted and effective attacks against that agent.
- Multi-Step Attack Chains
- Each action is simple and designed to be innocuous on its own, but is combined in a session to achieve a detrimental effect, taking advantage of the fact that most monitoring looks at actions from individual sessions.
- Memory and Context Manipulation
- Memory Poisoning attacks an agent's persistent memory to affect future interactions and cause it to behave differently, while Context Manipulation affects the information an agent trusts during a particular interaction to guide its next actions.
Key capabilities of production-ready prompt injection defense
Understanding the attack surface is only half the work; the other half is understanding what a defense platform needs to do to succeed against real production traffic and real attackers.
Agent and MCP-specific monitoring
Generic application monitoring was not built to handle tool calls, agent reasoning steps, or MCP message flows. Monitoring designed for these structures is essential to production-ready defense, combined with AI Discovery, which can find all the agents, MCP servers, and tool connections in an environment, even those that were not explicitly approved.
Continuous AI agent red teaming
AI Agent Red Teaming is a constant simulation of real attack techniques against real or simulated agents, mapped to frameworks such as the OWASP LLM Top 10, to ensure weaknesses are exposed in guardrails before an actual attacker finds them. A one-time static test only covers half the work, since both agents and the threat landscape are constantly changing.
CI/CD security validation
Injection resistance should not be a manual test performed before a major release; it should be checked automatically on any change to an agent, prompt, or tool configuration. Running security tests as part of CI/CD helps identify regressions in guardrail effectiveness early in the process.
Model-agnostic runtime protection
No enterprise standardizes on one model or one agent framework, and a defense that only works with one vendor's stack can become a blind spot the moment a team switches to a new one. AI runtime protection must work with a variety of LLMs, agent frameworks, and MCP implementations, so that changing or mixing these does not require redoing the security layer from scratch.
Audit trails and AI governance
All prompts, tool calls, and blocked actions must be recorded in a way that can be investigated, reported, and refined over time for compliance. AI Governance is essential for demonstrating what an agent did, why a block occurred, or whether a policy is truly having the desired effect.
How Akto delivers prompt injection defense
Akto brings AI agent discovery, continuous red teaming and runtime guardrails together, helping security teams find exposed workflows, test their defenses and protect agents in production.
Discover AI agents, MCP servers, and Shadow AI
Akto automatically discovers and catalogs AI agents, MCP servers, tools, and connected resources across cloud environments, employee endpoints, and internal infrastructure. That includes Shadow AI: agents, copilots, and MCP connections not officially approved or monitored by a security group, where the highest unmanaged risk is typically found.
Continuously test AI agents with red teaming
Akto automatically conducts continuous red teaming against AI agents, LLMs, and MCP servers, simulating real attack techniques such as prompt injection, inappropriate tool use, privilege escalation, and unsafe multi-step behavior. Tests are aligned with known standards such as the OWASP LLM Top 10, giving security teams a framework to validate guardrails rather than conducting manual tests.
Protect AI agents with runtime guardrails
Akto inspects agent interactions for prompt injection, credential exposure, sensitive data leakage and unsafe tool use. Configured guardrails can block policy violations before requests reach the model or tool, and screen responses before they move to the next step. Security teams can apply policies where their agents connect to models, gateways and MCP tools.
Which integrations does Akto offer to connect runtime protection to an agent stack?
Akto offers an integration to fit how agents call models and tools, applying security policies at different points in a production workflow.
| Integration | Where protection runs |
|---|---|
| MCP Gateway | Evaluates routed requests before forwarding them to MCP servers and analyzes responses before returning them to clients. |
| SDK/hooks integration | Checks model requests and responses, plus MCP tool arguments and results through the configured hooks. |
| Arcade | Checks tool inputs before execution and screens tool results before they return to the model. |
Routing MCP traffic through the gateway or enabling the appropriate guardrail hooks applies these policies to a workflow; the setup guides explain how to connect each one.
Enforce policies across AI agents and MCP tools
Akto applies consistent security policies across connected agent workflows, inspecting MCP requests and responses and protecting tool interactions, with policy decisions reviewable in the Akto dashboard. Teams can use these findings to investigate threats and tune protection as their agents, tools and business requirements change.
How should prompt injection protection be tested in production?
Testing prompt injection protection in production uses a staging copy of a real workflow, safe test data, and tools that cannot affect production accounts, run against the scenarios below before rollout.
| Scenario | What to verify |
|---|---|
| Direct injection | The verdict is recorded and a blocked request is not forwarded. |
| Malicious instructions in a tool result | The unsafe result is stopped before the next model step and does not trigger another action. |
| Unauthorized tool call or destination | Execution logs show whether the attempted action occurred. |
| Benign security discussion | Legitimate requests complete, with false positives recorded for review. |
| Guardrail outage | The workflow follows its configured fail-open or fail-closed behavior. |
| Streaming response | The test records any content delivered before a blocking decision. |
For a broader testing plan, read how to validate AI agent guardrails in production.
Building a runtime-first prompt injection defense strategy
Prompt injection cannot be fixed with a new filter at the front door. It needs multi-layered defense at all points of input, execution, and output; ongoing testing that keeps pace with how agents and attackers both develop; and runtime enforcement that can prevent a bad action from completing rather than explain what it did afterward. As agents become more autonomous and more tools connect through MCP, a runtime-first approach becomes more necessary. Akto unifies discovery, continuous red teaming, and runtime guardrails, giving security teams visibility and enforcement power for this threat in one platform designed for AI agents and MCP tools.