API ReferenceGuardrails

Guardrails API

v1.0BetaLast updated: March 2026

Scan AI agent inputs and outputs in real time to detect PII, secrets, prohibited content, and policy violations before they reach production.

⚠️

Beta: The Guardrails API is in beta. Endpoints and response schemas may change. We recommend pinning your SDK version.

Quick Start

import { init, guardrails } from '@thinkhive/sdk';
 
init({ apiKey: 'th_your_api_key' });
 
const result = await guardrails.scan({
  input: 'My email is john@example.com and SSN is 123-45-6789',
  scanners: ['pii'],
  config: {
    pii: { action: 'redact' }
  }
});
 
console.log(result.action);        // 'redact'
console.log(result.redactedInput);  // 'My email is [EMAIL] and SSN is [SSN]'

Authentication

All guardrails endpoints require an API key via the Authorization: Bearer header or X-API-Key header.

Authorization: Bearer th_your_api_key

See Authentication for details on obtaining and managing API keys.

Scan Content

POST /v1/guardrails/scan

Scan input, output, or tool calls against one or more scanners. Returns an action (pass, flag, redact, or block) and detailed findings.

Request Body

FieldTypeRequiredDescription
inputstringOne of input/output/toolCallUser input to scan
outputstringOne of input/output/toolCallAgent output to scan
toolCallobjectOne of input/output/toolCallTool call to validate ({ name, arguments })
scannersstring[]NoScanner names to run. Falls back to default policy if omitted.
policyIdstringNoNamed policy to apply. Overrides scanners if both provided.
configobjectNoPer-scanner configuration overrides
optionsobjectNoExecution options (see below)

At least one of input, output, or toolCall must be provided. You can scan multiple content types in a single request.

If neither scanners nor policyId is provided, the scan will use the company’s default active policy. If no default policy exists, a 400 error is returned.

Options

FieldTypeDefaultDescription
options.timeoutnumber5000Per-scanner timeout in milliseconds (100-30000)
options.failOpenbooleanfalseOn scanner timeout: true = pass, false = block
options.shortCircuitbooleanfalseStop scanning on first block result
options.returnRedactedbooleantrueInclude redacted content in response

Response

{
  "success": true,
  "data": {
    "action": "redact",
    "actionReason": "pii: email, ssn",
    "redactedInput": "My email is [EMAIL] and SSN is [SSN]",
    "results": {
      "pii": {
        "scanner": "pii",
        "status": "completed",
        "action": "redact",
        "findings": [
          {
            "type": "email",
            "value": "[EMAIL]",
            "start": 12,
            "end": 28,
            "confidence": 0.95
          },
          {
            "type": "ssn",
            "value": "[SSN]",
            "start": 37,
            "end": 48,
            "confidence": 0.95
          }
        ],
        "latencyMs": 2
      }
    },
    "metadata": {
      "scanId": "a1b2c3d4-...",
      "totalLatencyMs": 3,
      "scannersExecuted": 1,
      "scannersBlocked": 0,
      "scannersFlagged": 0,
      "scannersTimedOut": 0,
      "cached": false
    }
  }
}

Action Priority

When multiple scanners run, the highest-priority action wins:

PriorityActionMeaning
4 (highest)blockContent rejected — do not send
3redactContent modified — sensitive data replaced
2flagContent allowed but flagged for review
1 (lowest)passContent is clean

List Scanners

GET /v1/guardrails/scanners

Returns all available scanners with their descriptions.

{
  "success": true,
  "data": {
    "scanners": [
      { "name": "pii", "description": "Detects personally identifiable information" },
      { "name": "secrets", "description": "Detects API keys, tokens, and credentials" },
      { "name": "keywords", "description": "Matches against keyword blocklists" },
      { "name": "regex", "description": "Matches user-defined regex patterns" },
      { "name": "topic", "description": "Detects prohibited topics" },
      { "name": "tool_call", "description": "Validates tool calls against allow-lists" }
    ]
  }
}

Scanner Reference

PII Scanner

Detects personally identifiable information using pattern matching and entity recognition.

ConfigTypeDefaultDescription
entitiesstring[]allEntity types to detect: email, phone, ssn, credit_card, ip_address, date_of_birth, jwt, aws_key, private_key, password, bearer_token, basic_auth, connection_string, medical_record_number, health_plan_id, npi
actionstring"redact"Action on detection: redact, mask, block
{
  "scanners": ["pii"],
  "config": {
    "pii": {
      "entities": ["email", "ssn", "credit_card"],
      "action": "redact"
    }
  }
}

Secrets Scanner

Detects API keys, tokens, passwords, and other credentials using prefix matching and entropy analysis.

ConfigTypeDefaultDescription
actionstring"block"Action on detection: block, redact, flag
{
  "scanners": ["secrets"],
  "config": {
    "secrets": { "action": "block" }
  }
}

Detected patterns: AWS keys (AKIA...), GitHub tokens (ghp_, gho_, ghs_), Stripe keys (sk_live_, sk_test_), generic API keys, Bearer tokens, private keys, and high-entropy strings.

Keywords Scanner

Matches content against keyword blocklists using the Aho-Corasick algorithm for efficient multi-pattern matching.

ConfigTypeDefaultDescription
keywordsstring[]requiredKeywords to match
caseSensitivebooleanfalseCase-sensitive matching
{
  "scanners": ["keywords"],
  "config": {
    "keywords": {
      "keywords": ["competitor_name", "confidential", "internal only"],
      "caseSensitive": false
    }
  }
}

Regex Scanner

Matches user-defined regular expression patterns against content.

ConfigTypeDefaultDescription
patternsobject[]requiredArray of { pattern, name, action }
{
  "scanners": ["regex"],
  "config": {
    "regex": {
      "patterns": [
        {
          "pattern": "\\b[A-Z]{2}\\d{6}\\b",
          "name": "internal_id",
          "action": "flag"
        }
      ]
    }
  }
}

Topic Scanner

Detects prohibited or sensitive topics using built-in and custom topic definitions.

ConfigTypeDefaultDescription
topicsstring[]requiredBuilt-in topics to detect: medical_advice, legal_advice, financial_advice. Custom topics can be added via customTopics.
customTopicsobject[][]Custom topic definitions: { name, keywords[] }
thresholdnumber2Minimum unique keyword matches to trigger detection
{
  "scanners": ["topic"],
  "config": {
    "topic": {
      "topics": ["medical_advice", "legal_advice"],
      "customTopics": [
        {
          "name": "pricing_discussion",
          "keywords": ["discount", "pricing", "negotiate", "deal"]
        }
      ],
      "action": "block"
    }
  }
}

Tool Call Scanner

Validates tool calls against an allow-list with optional argument constraints.

ConfigTypeDefaultDescription
allowedToolsobject[]requiredAllowed tools with constraints
{
  "scanners": ["tool_call"],
  "toolCall": {
    "name": "delete_user",
    "arguments": { "userId": "123", "permanent": true }
  },
  "config": {
    "tool_call": {
      "allowedTools": [
        {
          "name": "delete_user",
          "requiredArgs": ["userId"],
          "blockedArgs": ["permanent"]
        }
      ]
    }
  }
}

Policies

Policies are named scan configurations that can be reused across requests. Create policies via the dashboard or API, then reference them by ID.

Create Policy

POST /api/guardrail-policies
{
  "name": "Production Input Filter",
  "description": "Standard input scanning for production agents",
  "scanners": [
    { "scanner": "pii", "config": { "action": "redact" } },
    { "scanner": "secrets", "config": { "action": "block" } },
    { "scanner": "keywords", "config": { "keywords": ["confidential"] } }
  ],
  "options": {
    "timeout": 3000,
    "failOpen": false,
    "shortCircuit": true
  },
  "isDefault": true
}

Use Policy in Scan

{
  "input": "Check order for john@example.com",
  "policyId": "policy_abc123"
}

When using a policyId, the scanners field is optional. Per-scanner config overrides in the request are merged with the policy’s configuration.

Policy Endpoints

MethodEndpointDescription
POST/api/guardrail-policiesCreate a new policy
GET/api/guardrail-policiesList all active policies
GET/api/guardrail-policies/:idGet a specific policy
PUT/api/guardrail-policies/:idUpdate a policy
DELETE/api/guardrail-policies/:idDeactivate a policy (soft delete)

SDK Examples

import { init, guardrails } from '@thinkhive/sdk';
 
init({ apiKey: process.env.THINKHIVE_API_KEY });
 
// Scan with multiple scanners
const result = await guardrails.scan({
  input: userMessage,
  output: agentResponse,
  scanners: ['pii', 'secrets', 'keywords'],
  config: {
    pii: { action: 'redact', entities: ['email', 'phone'] },
    secrets: { action: 'block' },
    keywords: { keywords: ['confidential', 'internal'] }
  },
  options: { timeout: 3000, shortCircuit: true }
});
 
if (result.action === 'block') {
  throw new Error(`Content blocked: ${result.actionReason}`);
}
 
if (result.action === 'redact') {
  // Use redacted content instead
  const safeInput = result.redactedInput ?? userMessage;
  const safeOutput = result.redactedOutput ?? agentResponse;
}
 
// Scan with a policy
const policyResult = await guardrails.scan({
  input: userMessage,
  policyId: 'policy_abc123'
});
 
// List available scanners
const scanners = await guardrails.listScanners();

Error Codes

StatusCodeDescription
400BAD_REQUESTMissing required fields or invalid scanner name
401UNAUTHORIZEDMissing or invalid API key
404NOT_FOUNDPolicy not found or inactive
409CONFLICTDuplicate policy name
413PAYLOAD_TOO_LARGEInput exceeds 100KB limit
429RATE_LIMIT_EXCEEDEDToo many requests
500INTERNAL_ERRORServer error

Rate Limits

PlanRequests/minMax scanners/request
Beta606
Pro3006
EnterpriseCustomCustom

Rate limits are applied per API key. Contact sales for enterprise rate limits.

Guardrail Analytics

GET /api/guardrail-analytics

Get aggregate analytics about guardrail scan activity across your organization.

Query Parameters:

ParameterTypeDescription
periodstringTime period: 24h, 7d, 30d (default: 7d)
agentIdstringFilter by agent

Response:

{
  "success": true,
  "data": {
    "totalScans": 15420,
    "byAction": {
      "pass": 12800,
      "redact": 1900,
      "flag": 520,
      "block": 200
    },
    "byScanner": {
      "pii": { "scans": 10200, "findings": 1800 },
      "secrets": { "scans": 8500, "findings": 150 },
      "keywords": { "scans": 6300, "findings": 420 },
      "topic": { "scans": 3100, "findings": 80 }
    },
    "avgLatencyMs": 4.2,
    "topFindings": [
      { "type": "email", "count": 950 },
      { "type": "phone", "count": 420 },
      { "type": "ssn", "count": 230 }
    ]
  }
}

Next Steps