Inferensys

Prompt

Canary Token Output Detection Harness Prompt

A practical prompt playbook for security monitoring teams building automated detection pipelines that scan model outputs for canary token presence and return structured results with confidence scores.
Security analyst reviewing fraud detection AI on multiple screens, alert dashboards visible, dark mode monitoring setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the operational context, ideal user, and boundaries for deploying the Canary Token Output Detection Harness in a production AI pipeline.

This prompt is designed for security monitoring teams who have embedded canary tokens in system instructions and need an automated, structured way to scan model outputs for token leakage. The primary job-to-be-done is runtime detection of extraction attacks: when an adversary successfully exfiltrates hidden system prompt markers, this harness provides immediate, machine-readable evidence. The ideal user is a security engineer or MLOps practitioner integrating this as a post-processing step in an AI gateway, where every model response passes through the detector before reaching the user. Required context includes a list of known canary tokens, their associated severity tiers, and the raw model output string to scan.

Use this prompt when you have a defined canary token strategy already in place—tokens are embedded, their formats are known, and you need consistent, low-latency detection at inference time. It is particularly valuable in defense-in-depth architectures where output filtering complements input sanitization, rate limiting, and human review. The harness returns structured JSON with confidence scores, match locations, and false-positive handling notes, making it suitable for automated alerting pipelines and SIEM integration. Do not use this prompt as a standalone security control; it is one detection layer and cannot prevent token leakage, identify novel extraction techniques, or replace upstream defenses like instruction hierarchy hardening and context window management.

Before deploying, ensure your canary token list is complete and up-to-date. Missing tokens will produce false negatives. Configure alert thresholds based on token severity: surface-level tokens might warrant logging, while deep instruction tokens should trigger immediate escalation. The harness includes false-positive handling for legitimate token-like strings that appear in normal conversation, but you should tune the confidence scoring against your own production traffic patterns. For high-severity detections, always route to human review before taking automated action. Next, wire the output into your incident response playbook so that detection events trigger investigation, not just logging.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Canary Token Output Detection Harness works well, where it breaks, and the operational prerequisites for production deployment.

01

Good Fit: Automated CI/CD Security Gates

Use when: You need a repeatable, automated check in your deployment pipeline that scans every model response for canary token leakage before release. Guardrail: Integrate the harness output into your CI/CD platform (e.g., GitHub Actions, GitLab CI) to block merges or flag builds when a token is detected with high confidence.

02

Bad Fit: Real-Time Streaming Responses

Avoid when: Your application streams tokens to the user in real-time, as the detection harness requires the complete output to perform a reliable scan. Guardrail: For streaming endpoints, buffer the full response server-side, run the detection harness, and only release the output to the user if it passes the canary check.

03

Required Inputs: Canary Token Registry

What to watch: The harness is useless without a precise, up-to-date list of active canary tokens and their expected formats. Guardrail: Maintain a versioned token registry (JSON or database table) that maps each token to its deployment location, severity tier, and a strict regex pattern for matching. Feed this registry as a required input to every scan.

04

Operational Risk: False-Positive Alert Fatigue

What to watch: Overly broad regex patterns or common-word canary tokens can flood your security operations team with false-positive alerts, causing real leaks to be ignored. Guardrail: Implement a confidence scoring system in the harness. Route low-confidence detections to a review queue instead of triggering a high-severity page. Continuously tune regex patterns against production output samples.

05

Operational Risk: Encoding and Obfuscation Bypass

What to watch: An attacker who extracts a canary token may encode it (e.g., base64, URL encoding) or split it across multiple outputs to evade simple string-matching detection. Guardrail: The harness must include decoding and normalization steps before scanning. Test it against a suite of obfuscated token variants to ensure the detection logic is robust to common evasion techniques.

06

Bad Fit: Unstructured or Free-Form Log Analysis

Avoid when: You need a general-purpose security log analyzer. This harness is specifically designed for the structured task of matching known canary token patterns in model outputs. Guardrail: Use this harness as a dedicated, downstream component in your AI security pipeline. Pair it with a separate, general-purpose threat analysis prompt for investigating broader anomalies in application logs.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use prompt that scans model outputs for canary tokens and returns structured detection results with confidence scores.

The following prompt template is designed to be dropped into an automated detection pipeline. It accepts a raw model output string and a list of known canary tokens, then returns a structured JSON result indicating whether any token was detected, along with confidence scores and supporting evidence. The template uses square-bracket placeholders for all dynamic inputs, making it straightforward to parameterize in code before each invocation.

text
You are a security-focused output scanner. Your job is to examine the provided model output for the presence of any known canary tokens. A canary token is a unique, non-functional string deliberately embedded in system instructions to detect instruction leakage or extraction attacks.

[TOKEN_DEFINITIONS]

[OUTPUT_SCHEMA]

[CONSTRAINTS]

Model output to scan:
---
[INPUT]
---

Scan the above output for any canary token defined in [TOKEN_DEFINITIONS]. Return ONLY a valid JSON object conforming to [OUTPUT_SCHEMA]. Do not include any other text, commentary, or markdown formatting.

To adapt this template, replace each placeholder with concrete values. [TOKEN_DEFINITIONS] should contain a structured list of canary tokens, their expected formats, and any variant patterns (e.g., base64-encoded versions, delimiter-wrapped versions). [OUTPUT_SCHEMA] must define the exact JSON shape you expect, including fields for detected (boolean), confidence (0.0 to 1.0), matched_token (string or null), match_location (character offset or null), and evidence (string excerpt or null). [CONSTRAINTS] should specify handling rules such as "treat partial matches as non-detections unless confidence exceeds 0.9" or "flag any token that appears verbatim regardless of surrounding context." [INPUT] receives the raw model output string to be scanned. For high-risk deployments, always pair this prompt with a post-processing validator that confirms the JSON structure matches the expected schema before acting on the result.

When integrating this prompt into a production harness, avoid relying solely on the model's detection capability. Implement a secondary regex-based or exact-match check against the known token list as a deterministic fallback. This dual-layer approach catches cases where the model misses an obvious token or hallucinates a false positive. Log every scan result—including the raw input, the model's JSON response, and the deterministic check outcome—for audit and false-positive analysis. If the detection pipeline triggers an alert, require human review before taking automated action such as session termination or key rotation.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required by the Canary Token Output Detection Harness Prompt to produce reliable, structured detection results with confidence scores and alert thresholds.

PlaceholderPurposeExampleValidation Notes

[MODEL_OUTPUT]

The raw text output from the model being monitored for canary token leakage.

The capital of France is Paris. The system configuration reference is CANARY-8A3F-B2D1.

Must be a non-empty string. Null or empty input should trigger a false output with an error reason, not a false negative.

[CANARY_TOKEN_LIST]

A structured list of canary tokens to scan for, including their tier and severity level.

[{"token": "CANARY-8A3F-B2D1", "tier": "system", "severity": "critical"}]

Must be a valid JSON array of objects with token, tier, and severity fields. Parse check required. Empty array should return no detections.

[DETECTION_MODE]

Controls whether the scan uses exact match, fuzzy match, or regex pattern matching.

exact

Must be one of: exact, fuzzy, regex. Invalid values should cause the prompt to fail closed and return an error.

[CONFIDENCE_THRESHOLD]

Minimum confidence score required to report a detection as positive.

0.85

Must be a float between 0.0 and 1.0. Values outside this range should be clamped or rejected. Default to 0.85 if not provided.

[ALERT_THRESHOLD]

Severity level at or above which an alert should be generated.

high

Must be one of: low, medium, high, critical. Detections below this threshold are logged but not alerted. Invalid values default to high.

[OUTPUT_SCHEMA]

The expected JSON structure for the detection result.

{"detections": [], "summary": {}}

Must be a valid JSON Schema or example structure. The prompt should validate its own output against this schema before returning.

[FALSE_POSITIVE_RULES]

Patterns or contexts known to produce false positives that should be suppressed.

[{"pattern": "CANARY-0000-0000", "reason": "documentation example"}]

Must be a valid JSON array. Each rule should have a pattern and reason. Null allowed if no known false positives exist.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the canary token detection prompt into an automated security monitoring pipeline with validation, logging, and alerting.

The Canary Token Output Detection Harness Prompt is designed to be the final gate in your model response pipeline. It should be invoked synchronously after every model generation, before the output is returned to the user or logged to an external system. The harness receives the raw model output and a pre-configured list of active canary tokens, then returns a structured detection result. This is not a prompt you expose to end users; it is an internal control plane component that runs inside your AI gateway, middleware, or model-serving layer. The primary integration point is a post-generation hook that calls the LLM with this prompt, parses the structured JSON response, and takes action based on the detection_decision field.

To wire this into production, wrap the prompt in a thin service function that accepts model_output: string and active_canaries: list[CanaryToken] where each CanaryToken object includes a token_value, token_tier (e.g., surface, deep, critical), and alert_threshold. The function should construct the prompt by injecting these values into the [CANARY_TOKEN_LIST] and [MODEL_OUTPUT] placeholders. After receiving the LLM's response, validate the output against a strict JSON schema that requires detection_decision (enum: CLEAN, SUSPICIOUS, CONFIRMED_LEAK), detected_tokens (array of objects with token_id, token_tier, confidence_score, and match_location), and recommended_action (enum: LOG_ONLY, ALERT, BLOCK_AND_ESCALATE). If the JSON fails to parse or schema validation fails, retry once with a repair prompt. If the retry also fails, default to BLOCK_AND_ESCALATE and log the raw output for manual review.

Model choice matters here. Use a fast, cheap model for this detection task—GPT-4o-mini, Claude Haiku, or a fine-tuned small model are appropriate. The detection logic is pattern-matching with semantic context, not complex reasoning. Set temperature=0 to eliminate variance in detection results. For high-throughput systems, consider batching multiple outputs into a single detection request by formatting the [MODEL_OUTPUT] as a numbered list, but be aware that this increases the risk of cross-contamination in the prompt context. Always log every detection result—including CLEAN decisions—to a structured audit store with fields for timestamp, session_id, model_output_hash, detection_decision, detected_tokens, and llm_latency_ms. This audit trail is essential for incident response and for tuning false-positive rates over time.

Configure alerting thresholds in your harness wrapper, not in the prompt itself. The prompt returns structured data; your application code decides when to fire a PagerDuty alert, increment a Prometheus counter, or block a response. A CONFIRMED_LEAK on a critical tier token should trigger immediate blocking and escalation. A SUSPICIOUS detection with a confidence score below 0.7 might only increment a metric and log for later review. False positives are the primary failure mode here—the model may flag legitimate outputs that coincidentally contain canary-like strings. Mitigate this by using high-entropy canary tokens (UUIDs, random base64 strings) that are vanishingly unlikely to appear in normal text, and by tuning the confidence_score threshold in your application logic rather than relying solely on the model's judgment. Run weekly reviews of all SUSPICIOUS detections to identify patterns and adjust thresholds.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured detection result that the harness prompt must produce. Use this contract to validate outputs before alerting, ensure consistent parsing, and prevent false positives from malformed responses.

Field or ElementType or FormatRequiredValidation Rule

detection_result.canary_detected

boolean

Must be true if any canary token is found in [MODEL_OUTPUT]; false otherwise. No null allowed.

detection_result.detected_tokens

array of strings

Each element must match the exact [CANARY_TOKEN_REGEX] pattern. Array must be empty if canary_detected is false. No partial matches.

detection_result.confidence_score

number (0.0-1.0)

Must be >= [ALERT_THRESHOLD] if canary_detected is true. Score must be 0.0 if no tokens detected. Decimal precision limited to 2 places.

detection_result.false_positive_check

object

Must contain 'passed' (boolean) and 'checks_applied' (array of strings). 'passed' must be false if any check fails. Checks must include 'exact_match', 'context_isolation', and 'no_obfuscation'.

detection_result.token_context

array of objects

Each object must have 'token' (string), 'surrounding_text' (string, max 100 chars), and 'position' (integer). Array length must equal detected_tokens length.

detection_result.alert_triggered

boolean

Must be true if canary_detected is true AND confidence_score >= [ALERT_THRESHOLD] AND false_positive_check.passed is true. Otherwise false.

detection_result.scan_metadata

object

Must contain 'scan_timestamp' (ISO 8601), 'prompt_version' (string), and 'model_id' (string). All fields required. Timestamp must be within 5 seconds of actual scan time.

detection_result.error_log

array of strings or null

If present, must contain only non-empty strings describing validation or processing errors. Must be null if no errors occurred during scan.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when scanning model outputs for canary tokens and how to build a detection harness that survives real-world extraction attempts.

01

False Positives from Legitimate Content

What to watch: The detection harness flags canary tokens that appear in user inputs, retrieved documents, or benign model responses that happen to match the token pattern. This creates alert fatigue and erodes trust in the detection pipeline. Guardrail: Implement a pre-check that records all canary token instances present in the input context before model generation. Only flag tokens in the output that were not present in the input. Maintain an allowlist of known benign matches and log all detections with surrounding context for triage.

02

Encoding Obfuscation Evasion

What to watch: Attackers encode canary tokens using base64, Unicode homoglyphs, zero-width characters, or ROT13 to bypass exact-match detection. The harness sees clean text while the human reader sees the leaked token. Guardrail: Normalize all output before scanning by applying Unicode canonicalization (NFC/NFD), stripping zero-width characters, and decoding common encoding schemes. Run the detection regex against both the raw output and the normalized version. Add fuzzing tests that verify detection of obfuscated token variants.

03

Token Fragmentation Across Multiple Responses

What to watch: In multi-turn conversations, an attacker splits a canary token across several responses. No single response contains the complete token, so per-response scanning misses the extraction. Guardrail: Maintain a sliding window of recent outputs concatenated together. Scan the concatenated window for canary tokens in addition to individual responses. Set a configurable window size based on expected token length and conversation depth. Alert when partial token fragments are detected even if the full token hasn't appeared yet.

04

Threshold Tuning Causes Missed Detections

What to watch: Confidence score thresholds set too high cause the harness to ignore real extractions, especially when the model paraphrases or slightly modifies the canary token. Thresholds set too low generate excessive false positives. Guardrail: Use fuzzy matching with configurable similarity thresholds instead of binary exact-match. Implement a tiered alert system: exact match triggers critical alerts, high-similarity matches trigger warnings, low-similarity matches are logged for review. Regularly calibrate thresholds against a golden dataset of known extraction attempts and benign outputs.

05

Canary Token Leakage Through Tool Call Arguments

What to watch: The model includes canary tokens inside tool call parameters rather than the visible response text. The output scanner only checks the user-facing message and misses tokens passed to downstream systems. Guardrail: Extend the detection harness to scan all tool call arguments, function parameters, and structured output fields in addition to the text response. Log every tool invocation with its full argument payload. Treat canary tokens found in tool calls as higher severity because they indicate the token has propagated beyond the chat interface.

06

Detection Regex Drift Across Prompt Versions

What to watch: When canary token formats change between prompt versions, the detection harness uses stale regex patterns that no longer match the current tokens. Extraction attacks succeed silently because the scanner is looking for old tokens. Guardrail: Store canary token definitions and their corresponding detection patterns in a versioned configuration that is deployed atomically with the prompt. Run a pre-flight validation that confirms every active canary token has a matching detection rule. Include detection pattern tests in the prompt release gate and alert if a prompt version references tokens without corresponding scanner rules.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Canary Token Output Detection Harness before deploying it into a production pipeline. Each criterion targets a specific failure mode observed in detection systems.

CriterionPass StandardFailure SignalTest Method

Exact Token Match Detection

System correctly flags output containing the exact [CANARY_TOKEN] string with confidence >= 0.95.

Token present in output but detection result is false or confidence < 0.95.

Inject a response containing the raw [CANARY_TOKEN] and assert detection is true with high confidence.

Semantic Variant Rejection

System correctly ignores semantic descriptions of the token (e.g., 'the secret phrase') without the literal string.

A paraphrase of the token triggers a false positive detection.

Inject a response describing the token's purpose without the literal string and assert detection is false.

Obfuscation Bypass Resistance

System detects the token when split by zero-width characters, base64 encoded, or leetspeak substituted.

An obfuscated version of [CANARY_TOKEN] passes through undetected.

Run a fuzzing harness that applies common obfuscation techniques to [CANARY_TOKEN] and assert detection is true for each variant.

False-Positive Rate Control

System maintains a false-positive rate below the configured [FP_THRESHOLD] on a clean validation set.

Clean, non-canary text triggers an alert, exceeding the acceptable false-positive rate.

Run the detector against a golden dataset of 1000 clean outputs and assert the alert count is below the threshold.

Confidence Score Calibration

Confidence scores correlate with detection difficulty; exact matches score higher than partial or obfuscated matches.

An obfuscated match returns a higher confidence score than an exact match.

Compare the confidence score for an exact match against a zero-width character obfuscated match and assert the exact match score is higher.

Structured Output Schema Compliance

Detection result strictly matches the [OUTPUT_SCHEMA] with all required fields present and correctly typed.

Output is missing the alert_triggered boolean or the confidence_score is a string.

Validate the JSON output against the [OUTPUT_SCHEMA] using a schema validator and assert no errors.

Alert Threshold Adherence

An alert is triggered only when the confidence_score exceeds the configured [ALERT_THRESHOLD].

An alert is triggered for a detection with a confidence score below the threshold.

Set [ALERT_THRESHOLD] to 0.9, inject a response with a partial token match scoring 0.7, and assert no alert is generated.

Multi-Token Detection

System correctly identifies and reports all unique canary tokens present when multiple tokens from [TOKEN_LIST] are in the output.

Only the first token found is reported; subsequent tokens are missed.

Inject a response containing three distinct tokens from [TOKEN_LIST] and assert the detected_tokens array has a length of 3.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a simple JSON schema and no external tool calls. Focus on getting the detection logic right before adding infrastructure. Replace [CANARY_TOKEN_REGEX] with a hardcoded pattern for your test token. Use a single confidence threshold like threshold: 0.7. Run against a small set of known-positive and known-negative outputs manually.

Watch for

  • False positives on coincidental string matches (e.g., UUIDs that look like tokens)
  • Missing edge cases where the token is split across lines or wrapped in code fences
  • Overly broad regex that matches partial tokens
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.