Recipes
Copy-paste guardrail patterns for real-world scenarios. Every recipe is tested and proven safe.
Context keys are yours to choose.
The built-in presets read environment; the hand-written
rules below read env. Either is fine — but the key in
your rule and the key in your context must match exactly. A mismatch
does not error, it just never fires.
Protect your database
Block all destructive database actions in production. One line.
import { productionSafety } from '@savants.dev/guard';
async function main() {
const guard = await productionSafety();
// Wrap your database tool
const safeDb = guard.wrap(async (params) => {
return await db.execute(params.query);
});
await safeDb({ action: 'select_users', environment: 'production' });
// ✓ Allowed — read-only
await safeDb({ action: 'delete_table', environment: 'production' });
}
// ✗ Throws GuardError — blocked before execute() Guard Vercel AI SDK tools
Wrap all your AI tools in one line. Works with generateText, streamText and agents.
This example targets AI SDK 5+, where the tool argument is inputSchema. On AI SDK 4 and earlier the same field was called parameters; the guard works identically either way.
import { generateText, tool } from 'ai';
import { z } from 'zod';
import { createGuard } from '@savants.dev/guard';
const guard = await createGuard([
"when action contains 'delete' and env eq 'production' then block",
"when action contains 'delete' and user_count gt 10 then require_approval",
]);
const tools = guard.wrapTools({
deleteUser: tool({
description: 'Delete a user',
inputSchema: z.object({ userId: z.string(), env: z.string() }),
execute: async ({ userId }) => db.users.delete(userId),
}),
});
// Zod validates the shape. Guards validate the safety.
// Both must pass, and both are checked before the call runs. Spend limits for AI agents
Prevent your agent from making purchases without approval.
import { spendLimit } from '@savants.dev/guard';
async function main() {
const guard = spendLimit(25);
guard.check({ amount: 5.99, item: 'eggs' });
// ✓ Allowed — under limit
guard.check({ amount: 31.43, item: 'eggs with delivery' });
// ✗ Blocked — $31.43 > $25
}
// This is the OpenAI Operator egg purchase, prevented. No deploys on Friday
Because Friday deploys ruin weekends.
import { createGuard } from '@savants.dev/guard';
async function main() {
const guard = await createGuard([
"when action contains 'deploy' and day_of_week eq 'Friday' and risk_score gt 0.7 then block",
"when action contains 'deploy' and test_pass_rate lt 100 then block",
]);
// In your CI/CD pipeline:
const today = new Date().toLocaleDateString('en-US', { weekday: 'long' });
const result = guard.check({
action: 'deploy_to_production',
day_of_week: today,
risk_score: 0.85,
test_pass_rate: 100,
});
if (result.blocked) {
console.log('Deploy blocked:', result.rule);
process.exit(1);
}
} Audit trail for compliance
Every check() is recorded in memory and getLog() returns the list. It is a process-local array, not a durable audit log — nothing is written to disk and the log dies with the process. Ship it somewhere yourself if you need it to survive a restart.
const guard = await createGuard([
async function main() {
"when action contains 'delete' then block",
"when action contains 'send' then suggest",
]);
// Every check is logged automatically
guard.check({ action: 'delete_user', user_id: '123' });
guard.check({ action: 'send_email', to: 'ceo@company.com' });
guard.check({ action: 'read_report' });
// Get the full audit trail
const log = guard.getLog();
}
console.log(JSON.stringify(log, null, 2)); Custom rules at runtime
Start with defaults, add company-specific rules without redeploying.
const guard = await productionSafety();
async function main() {
// Add company-specific rules at runtime
guard.addRule("when department eq 'finance' and amount gt 10000 then require_approval");
guard.addRule("when data_classification eq 'pii' and action contains 'export' then block");
// See all active rules
}
console.log(guard.listRules());