Skip to Content
ZeroLeaksDocs
Shield SDKProvider wrappers

AI SDK tools

Let a model inspect text for prompt injection with the shieldCheck tool on AI SDK 5, 6, and 7, using local or hosted detection.

shieldCheck inspects user messages, retrieved documents, web pages, emails, and tool results for prompt injection and jailbreaks. It runs locally with no API key or network request unless you configure hosted detection.

Use @zeroleaks/shield 2.1.2 or later with AI SDK 5, 6, or 7. The language model middleware also supports AI SDK 4.

Install

bun add @zeroleaks/shield ai zod

AI SDK requires Zod as a peer dependency even when a tool uses JSON Schema. AI SDK 7 requires Node.js 22 or later; earlier SDK versions have their own runtime requirements.

The tool uses its own /ai-sdk/tools entry point and is not exported from the package root. Other Shield integrations work without ai installed.

Usage

This AI SDK 7 example uses the default AI Gateway provider. Set AI_GATEWAY_API_KEY for the model call. Local Shield detection needs no ZeroLeaks API key.

import { gateway, generateText, isStepCount, wrapLanguageModel } from 'ai';
import { shieldLanguageModelMiddleware } from '@zeroleaks/shield/ai-sdk';
import { shieldCheck } from '@zeroleaks/shield/ai-sdk/tools';

const model = wrapLanguageModel({
  model: gateway('openai/gpt-6.1-sol'),
  middleware: shieldLanguageModelMiddleware(),
});

const { text } = await generateText({
  model,
  tools: { shieldCheck: shieldCheck() },
  stopWhen: isStepCount(3),
  prompt:
    'Check this support note with shieldCheck, then summarize it: Our support desk opens at nine on Monday.',
});

console.info(text);

The middleware checks text in user messages and tool results before each model call and blocks detected injections by default. The tool alone can't enforce a check; see Limitations.

On AI SDK 5 and 6, use stepCountIs instead of isStepCount. You can also supply a provider model instead of a Gateway model string.

Check content before adding it to context

For a document entering through a path the middleware does not inspect, call the executor from your application with the original text:

import { InjectionDetectedError } from "@zeroleaks/shield";
import { shieldCheck } from "@zeroleaks/shield/ai-sdk/tools";

const check = shieldCheck();
const verdict = await check.execute(
  { text: "The document's complete original text.", source: "document" },
  {}
);

if (verdict.detected) {
  throw new InjectionDetectedError(verdict.risk, verdict.categories);
}

// Apply your application's access and tool policies before using the document.

See Fields scanned and guarded for the content shapes the middleware inspects. Authorization, human approval, and network restrictions belong in your application's tool policies.

Hosted detection

Hosted detection is explicit. A ZEROLEAKS_API_KEY in the environment does not switch shieldCheck() away from local detection. Keep hosted Shield API keys on your server.

import { shieldCheck } from "@zeroleaks/shield/ai-sdk/tools";

const check = shieldCheck({
  hosted: {
    apiKey: process.env.ZEROLEAKS_API_KEY,
    model: "shield",
    timeoutMs: 10_000,
  },
});

const verdict = await check.execute(
  { text: "The document's complete original text.", source: "web" },
  {}
);

Create an API key in Shield API in your dashboard. The free shield model requires research acknowledgement; flagged free-tier inputs may contribute redacted excerpts of up to 2,000 characters to security research and to training Shield models, kept for up to 12 months. Redaction is best effort; do not submit sensitive content you cannot permit to be retained. shield-base, shield-large, and shield-tiered require a paid plan or pay as you go. Paid requests are excluded from research retention unless they use a :contribute model ID. See models and access.

You can also pass an existing createHostedDetector() instance as hosted. For hosted middleware, pass the detector's .options() to both detect and scanToolResults; configuring a hosted tool does not change the middleware's detector. See the hosted AI SDK integration.

Options

shieldCheck() accepts description and either detect for local detection options, or hosted for hosted options or a reusable detector. Asynchronous local detectors are awaited. Local and hosted options cannot be combined.

Input

The input is { text: string, source?: string }. source accepts user, tool_result, document, web, email, or mcp_tool_description. It is informational and does not change detection or establish trust. Inspecting a tool description as text does not perform the structural checks offered by scanTools.

Returns

Result fieldMeaning
detectedWhether the configured detector flagged an injection
risknone, low, medium, high, or critical
scoreLocal classifier score, when available; hosted effective binary score. Scores from different detectors are not interchangeable.
categoriesUnique detected category names; hosted detection uses the binary prompt_injection category
enginelocal or hosted
sourceThe supplied informational label, when present
model, modelScore, rules, coverageHosted model ID, raw model score, rules flag, and window coverage

Results omit the original text and matching patterns. The AI SDK still records tool arguments in messages, results, and optional telemetry; configure your logging accordingly.

Handle errors

Hosted authentication failures, rate limits, timeouts, cancellation, and invalid responses throw rather than returning a negative detection. Pass { abortSignal } as the executor's second argument to cancel a check. AI SDK supplies its cancellation signal automatically, and the tool forwards it to hosted requests.

An error thrown by an AI SDK tool becomes a tool-error the model can receive in a later step. It does not automatically stop the agent. Enforce whether actions may continue in application code or middleware, and never interpret a failed check as a successful inspection. See AI SDK error handling.

Limitations

  • The model chooses whether to call shieldCheck and what text to submit, so the tool alone cannot enforce inspection of a complete document or prevent an action.
  • A negative result means no injection was detected under the configured checks; it does not guarantee safety or grant permission to use a tool.
  • Local checks reject text longer than detect.maxInputLength, which defaults to 1,048,576 UTF-16 code units. They never return a verdict for silently truncated input.
  • Empty text, unsupported source labels, and extra input fields are rejected.
  • Hosted checks also enforce service request limits and always require complete coverage. Partial or missing coverage raises SHIELD_INCOMPLETE_COVERAGE, including with an existing detector. There is no partial-coverage opt-out.
  • A synchronous local scan cannot be interrupted while running. Asynchronous local checks test cancellation before returning.

On this page