Skip to content

Prompt injection detection for Mastra

Arcjet prompt injection detection evaluates each incoming prompt for injection patterns inside your application before it reaches the AI provider. Detected attacks are blocked before the AI call is made, protecting both your application behavior and your AI budget.

What is Arcjet? Arcjet is the runtime security platform that ships with your code. Enforce budgets, stop prompt injection, detect bots, and protect personal information with Arcjet's AI security building blocks.

This example screens inbound user text for prompt injection before the model runs.

We assume you already have a Mastra project set up. For helper options and denial behavior, see the Mastra agent guard.

Install the dependencies:

Terminal window
# Export your Arcjet API key from https://console.arcjet.com
export ARCJET_KEY="ajkey_..."
npm install @arcjet/guard @mastra/core

Create the example:

agent.ts
import { launchArcjet, detectPromptInjection } from "@arcjet/guard";
import { guardProcessor } from "@arcjet/guard/mastra/v1";
import { Agent } from "@mastra/core/agent";
const arcjet = launchArcjet({ key: process.env.ARCJET_KEY! });
const inbound = guardProcessor(arcjet, {
action: "message.received",
rules: ({ text }) => [detectPromptInjection()(text)],
});
export const agent = new Agent({
id: "support-agent",
name: "support-agent",
instructions: "Help the user.",
model: "openai/gpt-4o-mini",
inputProcessors: [inbound],
});

Then start or invoke the agent with a test prompt.

Requests appear in your Arcjet dashboard in real time.

Need help with anything? Email support@arcjet.com to get support from our engineering team.

Discussion