agentsclimarketplace

Guardrails

Skill ravi2799/ai-agent-skills/skills/guardrails

Skills that help AI agents build better AI agents — prompt engineering, architecture, evaluation, and more.

Install
npx -y skills add ravi2799/ai-agent-skills --skill guardrails

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

One thing to look at

  • 3 stars3 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

What its author says it does

Copied from the file, not written here

Use this skill when adding safety rails, input validation, or output checks to AI agent systems. Triggers include "add guardrails", "make this agent safe", "validate agent output", "prevent prompt injection", "add safety checks", "rate limit the agent", "restrict agent actions", or any task involving agent safety, input sanitization, output filtering, or action gating.

SKILL.md

7.8 KB, as published. Nobody here has run it

Guardrails Skill

A skill that governs how to design, implement, or audit safety guardrails for AI agent systems.

Identify which operation applies, then follow the corresponding section.


Operation: DESIGN — Designing Guardrails

Pre-Design Checklist

Before adding guardrails, verify:

  • I have identified the risk categories for this agent (data leakage, harmful output, unauthorized actions, injection)
  • I know the blast radius of agent actions — what is reversible vs irreversible
  • I have defined acceptable vs unacceptable agent behavior
  • I know the trust boundary — what input sources are untrusted

Guardrail Categories

1. Input Validation

Sanitize and validate all input before the agent processes it.

CheckWhat It CatchesImplementation
Schema validationMalformed inputJSON Schema / type checks
Length limitsContext overflow attacksMax character/token count
Injection detectionPrompt injection attemptsPattern matching + classifier
Encoding checkUnicode/encoding exploitsNormalize to UTF-8

2. Output Filtering

Validate agent output before returning to the user.

CheckWhat It CatchesImplementation
PII detectionLeaked personal dataRegex for emails, phones, SSNs + NER
Content classificationHarmful or inappropriate contentClassifier or keyword filter
Format complianceWrong output structureSchema validation
Hallucination indicatorsFabricated factsConfidence scoring, source verification
Consistency checkContradictory statementsCompare against input context

3. Action Gating

Classify agent actions by risk level and gate accordingly.

Risk LevelExamplesGate
SafeRead files, search, run testsAuto-approve
ModerateWrite files, create branchesLog + proceed
HighDelete files, push code, send messagesRequire user confirmation
CriticalDrop tables, force push, deploy to productionRequire explicit approval + reason

Key principle — reversibility determines risk level.

  • Reversible actions (create a branch, write a file) → lower risk
  • Irreversible actions (delete data, send email, deploy) → higher risk

4. Rate Limiting

Prevent runaway behavior.

LimitPurposeTypical Value
Max tool calls per turnPrevent infinite loops10-25 calls
Max consecutive failuresStop futile retries3 failures
Max tokens per responseControl costModel-dependent
Max execution timePrevent hung agents5-10 minutes
Max file operationsPrevent mass changes20 files per task

5. Scope Boundaries

Restrict what the agent can access.

  • File system — allowlist of directories, deny patterns (e.g., **/.env, **/credentials*)
  • Network — allowlist of domains/APIs the agent can call
  • Database — read-only access by default, write access per-table
  • External services — no sending messages/emails without confirmation

Operation: IMPLEMENT — Adding Guardrails to Code

Pattern 1 — Pre-Execution Check

Validate before a tool call runs.

def pre_check(tool_name, arguments):
    # Block dangerous file paths
    if tool_name == "write_file":
        path = arguments.get("path", "")
        if any(p in path for p in [".env", "credentials", "secrets"]):
            return {"blocked": True, "reason": "Cannot write to sensitive files"}

    # Rate limit
    if call_count[tool_name] > MAX_CALLS:
        return {"blocked": True, "reason": f"Rate limit exceeded for {tool_name}"}

    return {"blocked": False}

Pattern 2 — Post-Execution Check

Validate output before returning to user.

def post_check(output):
    # PII detection
    if contains_pii(output):
        return redact_pii(output)

    # Format validation
    if not matches_schema(output, expected_schema):
        return {"error": "Output format invalid", "raw": output}

    return output

Pattern 3 — Circuit Breaker

Stop agent after repeated failures.

consecutive_failures = 0
MAX_FAILURES = 3

def on_tool_result(result):
    if result.is_error:
        consecutive_failures += 1
        if consecutive_failures >= MAX_FAILURES:
            return stop_agent("Circuit breaker: {MAX_FAILURES} consecutive failures")
    else:
        consecutive_failures = 0

Pattern 4 — Approval Gate

Pause for human approval on high-risk actions.

HIGH_RISK_TOOLS = ["delete_file", "push_to_remote", "send_email", "deploy"]

def before_tool_call(tool_name, arguments):
    if tool_name in HIGH_RISK_TOOLS:
        approved = request_user_approval(
            action=tool_name,
            details=arguments,
            reason="This action is irreversible"
        )
        if not approved:
            return {"blocked": True, "reason": "User denied"}

Pattern 5 — Audit Log

Record all agent decisions for review.

def log_action(event_type, details):
    log_entry = {
        "timestamp": now(),
        "event": event_type,    # tool_call, handoff, decision, error
        "agent": current_agent,
        "details": details,
        "context_size": token_count(current_context)
    }
    append_to_audit_log(log_entry)

Operation: AUDIT — Reviewing Existing Guardrails

Evaluation Dimensions

DimensionScore 1Score 5
Input validationNo validationSchema + injection + length checks
Output filteringNo checksPII + content + format checks
Action gatingAll actions auto-approvedRisk-tiered with confirmation gates
Scope boundariesUnrestricted accessAllowlisted paths, domains, tables
Rate limitingNo limitsTool calls, time, and cost capped
LoggingNo audit trailAll decisions and actions logged

Output Format

## Guardrails Audit Report

### Scores
| Dimension         | Score (1-5) | Notes |
|-------------------|-------------|-------|
| Input validation  |             |       |
| Output filtering  |             |       |
| Action gating     |             |       |
| Scope boundaries  |             |       |
| Rate limiting     |             |       |
| Logging           |             |       |

### Overall Score: X / 30

### Critical Gaps
- ...

### Recommendations (priority order)
1. ...
2. ...

Red Team Checklist

Test these attack vectors:

  • Prompt injection via user input — does the agent follow injected instructions?
  • Path traversal — can the agent access files outside allowed directories?
  • Sensitive data extraction — does the agent leak PII, API keys, or credentials?
  • Privilege escalation — can the agent be tricked into high-risk actions without confirmation?
  • Resource exhaustion — can input cause infinite loops or excessive API calls?
  • Output manipulation — can the agent be made to produce harmful content?

What NOT To Do

  • Ship an agent with no guardrails and plan to "add them later"
  • Use over-permissive defaults (default should be restrictive)
  • Trust all tool results without validation
  • Implement guardrails that can be bypassed by rephrasing
  • Log sensitive data (PII, credentials) in audit logs
  • Gate every action — too many confirmations cause user fatigue
  • Rely solely on the model's built-in safety for application-specific risks

Keep looking

Skills are one crate of 328,083. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.