Documentation

Integration guide

Three proven integration points: inline middleware before your model call, a CLI bridge from non-Node stacks, and CI gates for prompt libraries.

Express: block before the model call

Score every prompt inline and reject anything at or above the high band (score ≥ 50). A runnable version lives in examples/integration_demo.

import express from "express";
import { scanInput } from "./src/lib/scanner";

const app = express();
app.use(express.json());

app.post("/chat", async (req, res) => {
  const prompt = String(req.body?.prompt ?? "");
  const scan = scanInput(prompt);
  if (!scan.success) {
    return res.status(500).json({ error: scan.error ?? "scan_failed" });
  }

  if (scan.analysis.score >= 50) {
    return res.status(422).json({
      message: "Prompt blocked by Prompt Defenders",
      advisories: scan.analysis.advisories,
    });
  }

  const reply = await callYourLLM(prompt); // your own LLM adapter
  return res.json({ reply, scan });
});

FastAPI (or any stack) via the CLI

Non-Node services can pipe prompts to prompt-defender scan - over stdin and parse the JSON report. Run it from a clone of this repo (the CLI is not yet published to npm).

import json
import subprocess
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class Prompt(BaseModel):
    text: str

def run_prompt_defender(prompt: str) -> dict:
    proc = subprocess.run(
        ["npx", "prompt-defender", "scan", "-"],
        input=prompt.encode("utf-8"),
        capture_output=True,
        check=False,
    )
    if proc.returncode != 0:
        raise HTTPException(status_code=500, detail=proc.stderr.decode())
    return json.loads(proc.stdout)

Fail builds on risky prompt templates

Scan seed prompts (system messages, scripted flows) in your pipeline and fail the build when the report crosses your threshold:

name: prompt-defenders
on: [push, pull_request]

jobs:
  scan-prompts:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - name: Scan scripted prompts
        run: |
          npx prompt-defender scan prompts/signup_flow.txt --rules basic > scan-report.json
          node scripts/check-scan.js scan-report.json
import { readFileSync } from "node:fs";

const report = JSON.parse(readFileSync(process.argv[2], "utf8"));
if (report.risk_score >= 50) {
  console.error("Prompt Defenders detected high-risk patterns:", report.issues);
  process.exit(1);
}
console.log("Prompts look clean", report.risk_score);

Or gate prompt fixtures directly inside tests:

import { scanInput } from "../src/lib/scanner";

it("marketing copy fixtures stay clean", () => {
  const report = scanInput(loadMarketingTemplate());
  expect(report.success).toBe(true);
  expect(report.analysis.score).toBeLessThan(20);
});
  • Treat risk_score >= 50 as a blocking threshold.
  • Upload the scan report as a build artifact so reviewers can inspect advisories.
  • Full guide: docs/ci_integration.md