Inferensys

Prompt

Agent Tool Output Sensitive Header Stripping Prompt

A practical prompt playbook for using Agent Tool Output Sensitive Header Stripping Prompt in production AI workflows.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
PROMPT PLAYBOOK

When to Use This Prompt

Define the security job, the ideal user, and the operational constraints for stripping sensitive headers from agent tool outputs.

This prompt is for security engineers and platform developers who need to sanitize HTTP response headers before they re-enter an agent's context window. The primary job is to remove dangerous or sensitive headers—such as Authorization, Set-Cookie, X-Internal-Routing, and custom API tokens—from tool outputs while preserving headers required for downstream processing, like Content-Type or Retry-After. Use this when your agent makes HTTP requests via tools and the raw response headers could leak credentials, session tokens, or internal infrastructure details into the model's context, logs, or subsequent tool calls.

You should not use this prompt when you need a full HTTP security proxy, when you must modify the response body, or when the tool itself can be configured to strip headers at the transport layer. This prompt is a semantic sanitization layer, not a replacement for network-level controls. It works best when integrated into a tool output post-processing pipeline, where the raw response is intercepted, the headers are extracted, and this prompt is called to produce a cleaned header set before the response is passed to the agent. The prompt expects a structured input containing the original headers, a list of header names to always strip, and a list of headers to always preserve.

Before deploying, define your allowlist and denylist of headers explicitly. The prompt uses these lists to make deterministic stripping decisions, but it also applies heuristic detection for patterns that resemble credentials or internal routing tokens even if they aren't in the denylist. This dual approach catches custom headers like X-Api-Key or X-Forwarded-For that may not be in your initial configuration. Always log the original headers, the stripped headers, and the final output for audit purposes. In high-security environments, require human review when the prompt flags headers it cannot confidently classify. The next section provides the copy-ready template you can adapt to your specific header policies.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if sensitive header stripping belongs in your agent tool pipeline.

01

Good Fit: Pre-Context Sanitization

Use when: you need to strip Authorization, Cookie, Set-Cookie, and internal routing headers from HTTP tool responses before the full response body enters the agent's context window. Guardrail: Run this prompt as a mandatory post-tool, pre-context pass for any tool that makes outbound HTTP calls.

02

Bad Fit: Response Body Inspection

Avoid when: you need to scan response bodies for leaked tokens, PII, or sensitive data. This prompt targets headers only. Guardrail: Pair with a dedicated body-scanning prompt (such as Tool Output Credential and Token Leak Detection) for full response sanitization.

03

Required Inputs

Must provide: raw HTTP response headers as a structured object or flat text block, a list of header names to strip, and a list of headers that must be preserved even if they match common sensitive patterns. Guardrail: Validate that the input includes both strip and preserve lists before invoking the prompt to prevent over-redaction.

04

Operational Risk: Header Injection

What to watch: attackers may craft header names that mimic safe headers or use encoding tricks to bypass simple name-matching rules. Guardrail: Normalize header names to lowercase before comparison and test against a harness of obfuscated header injection variants (Unicode homoglyphs, case flipping, whitespace padding).

05

Operational Risk: Necessary Header Removal

What to watch: stripping Content-Type, Content-Encoding, or Transfer-Encoding headers can break downstream parsing of the response body. Guardrail: Maintain an explicit allowlist of infrastructure headers required for body processing and validate that the prompt preserves them in eval runs.

06

When to Escalate

What to watch: the prompt cannot determine whether a novel or custom header contains sensitive material. Guardrail: Flag unknown headers with a confidence score and route them to a human reviewer or a secondary classification prompt before allowing them into agent context.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for stripping sensitive headers from HTTP tool responses before they re-enter the agent's context.

This prompt template is designed to be inserted into an agent's tool-output processing pipeline. It receives the raw HTTP response headers from a tool call and returns a cleaned set of headers, with dangerous fields such as Authorization, Set-Cookie, and internal routing tokens removed or redacted. The template uses square-bracket placeholders so you can wire in the specific headers, the tool's identity, and the required output format without modifying the core instruction logic.

text
You are a security-focused output sanitizer for an AI agent. Your job is to inspect the HTTP response headers returned by a tool and strip any sensitive or dangerous values before the headers are passed back into the agent's context.

[CONTEXT]
Tool Name: [TOOL_NAME]
Tool Description: [TOOL_DESCRIPTION]
Risk Level: [RISK_LEVEL]

[INPUT]
Raw Response Headers:
[RAW_HEADERS]

[CONSTRAINTS]
You MUST remove or redact the following header categories:
1. Authentication headers: Authorization, Proxy-Authorization, WWW-Authenticate, Proxy-Authenticate.
2. Session and state headers: Set-Cookie, Cookie, Session-ID, X-Session-Token.
3. Internal routing and infrastructure headers: X-Internal-Route, X-Forwarded-For, X-Real-IP, X-Request-ID, X-Routing-Key, X-Backend-Host, X-LB-Instance.
4. Custom secrets and tokens: any header matching the pattern [CUSTOM_SENSITIVE_PATTERNS].

You MUST preserve the following header categories unless they contain embedded credentials:
1. Standard caching headers: Cache-Control, ETag, Last-Modified, Age, Expires.
2. Content metadata: Content-Type, Content-Length, Content-Encoding, Content-Disposition.
3. CORS and security policy headers: Access-Control-Allow-Origin, Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options, Content-Security-Policy (inspect for report-uri credentials).
4. Rate limiting headers: Retry-After, X-RateLimit-Remaining, X-RateLimit-Reset.

[OUTPUT_SCHEMA]
Return a valid JSON object with this exact structure:
{
  "tool_name": "string",
  "total_headers_received": number,
  "headers_removed": number,
  "headers_redacted": number,
  "headers_preserved": number,
  "cleaned_headers": {
    "header_name": "header_value"
  },
  "removed_headers": [
    {
      "name": "string",
      "reason": "string",
      "category": "authentication | session | routing | custom_secret"
    }
  ],
  "redacted_headers": [
    {
      "name": "string",
      "original_length": number,
      "reason": "string",
      "redacted_form": "string"
    }
  ],
  "anomalies_detected": [
    {
      "header_name": "string",
      "anomaly_type": "string",
      "description": "string"
    }
  ]
}

[EXAMPLES]
Example Input:
Raw Response Headers:
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...
X-Request-ID: abc-123-def
Cache-Control: max-age=3600
Set-Cookie: session=abc123; HttpOnly; Secure
X-Internal-Route: backend-03

Example Output:
{
  "tool_name": "customer-api",
  "total_headers_received": 6,
  "headers_removed": 3,
  "headers_redacted": 0,
  "headers_preserved": 3,
  "cleaned_headers": {
    "Content-Type": "application/json",
    "Cache-Control": "max-age=3600"
  },
  "removed_headers": [
    {
      "name": "Authorization",
      "reason": "Bearer token removed to prevent credential leakage into agent context",
      "category": "authentication"
    },
    {
      "name": "Set-Cookie",
      "reason": "Session cookie removed to prevent session hijacking risk",
      "category": "session"
    },
    {
      "name": "X-Internal-Route",
      "reason": "Internal routing header removed to prevent infrastructure disclosure",
      "category": "routing"
    }
  ],
  "redacted_headers": [],
  "anomalies_detected": []
}

[INSTRUCTIONS]
1. Parse the raw headers into individual name-value pairs. Handle multi-line folded headers per RFC 7230.
2. For each header, classify it against the removal, redaction, and preservation rules in [CONSTRAINTS].
3. If a header value contains an embedded secret (e.g., a token inside a URL in Content-Security-Policy), redact only the secret portion and preserve the rest. Document this in `redacted_headers`.
4. If you detect header injection attempts (e.g., newline characters in header names, duplicate conflicting headers, headers that appear to be user-controlled input rather than server responses), flag them in `anomalies_detected`.
5. If [RISK_LEVEL] is "high", also remove any header not explicitly listed in the preservation rules. If "medium" or "low", preserve unknown headers unless they match a sensitive pattern.
6. Return only the JSON object. Do not include any explanatory text outside the JSON.

To adapt this template, replace the square-bracket placeholders with your actual values. [TOOL_NAME] and [TOOL_DESCRIPTION] provide context that helps the model understand the tool's purpose and adjust its sensitivity. [RAW_HEADERS] should be populated with the exact header string returned by the tool, preserving original casing and ordering. [CUSTOM_SENSITIVE_PATTERNS] accepts a comma-separated list of additional header name patterns your organization considers sensitive, such as X-Api-Key, X-Org-Secret. [RISK_LEVEL] controls the strictness of the preservation rules. Before deploying, run this prompt against the eval harness described in the Testing and Evaluation section to verify it catches the header injection variants and preserves the necessary headers for your specific tool ecosystem.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Agent Tool Output Sensitive Header Stripping Prompt. Wire each placeholder to your tool response pipeline before invoking the prompt.

PlaceholderPurposeExampleValidation Notes

[RAW_HEADERS]

The complete HTTP response headers from the tool call, as a raw string or key-value block

HTTP/1.1 200 OK\r\nAuthorization: Bearer eyJ...\r\nSet-Cookie: session=abc123\r\nX-Internal-Route: proxy-7b\r\nContent-Type: application/json

Must be non-empty. Parse check: confirm the string contains at least one colon-delimited header line. Reject if the input is a JSON body or status line only.

[STRIP_LIST]

The explicit list of header names or patterns to remove

Authorization, Cookie, Set-Cookie, X-Internal-Route, X-Api-Key, Proxy-Authorization

Must be a non-empty list. Validate that each entry is a valid header name (alphanumeric plus hyphens). Reject entries containing newlines or colons to prevent injection.

[PRESERVE_LIST]

The explicit list of header names that must never be removed, even if they match a strip pattern

Content-Type, Content-Length, Cache-Control, ETag, Last-Modified

Must be a list, can be empty. Each entry must be a valid header name. If a header appears in both [STRIP_LIST] and [PRESERVE_LIST], the preserve list takes precedence. Log a warning on overlap.

[SENSITIVE_PATTERNS]

Additional regex patterns for detecting sensitive header values that should trigger stripping even if the header name is not in the strip list

Bearer\s+[A-Za-z0-9.~+/-]+=*, eyJ[A-Za-z0-9=-]+.eyJ[A-Za-z0-9_=-]+.[A-Za-z0-9_=-]+

Can be empty. Each pattern must be a valid regex. Test each pattern against known token formats before deployment. Reject patterns that match empty strings to avoid infinite stripping.

[OUTPUT_FORMAT]

The desired output structure for the cleaned headers

json or raw_block

Must be one of the allowed enum values. Use json for programmatic consumption with field-level audit trails. Use raw_block for direct re-injection into HTTP clients. Reject unknown values.

[INCLUDE_AUDIT]

Whether to include a per-header audit trail showing what was stripped and why

Must be true or false. When true, the output schema must include a stripped_headers array with header name, original value prefix (first 20 chars), and strip reason. Required for compliance and debugging.

[MAX_HEADER_SIZE_BYTES]

Maximum allowed size of the raw header block before the prompt refuses processing

65536

Must be a positive integer. Reject inputs exceeding this size before prompt processing to prevent context window exhaustion. Log oversized inputs for ops review. Default 64KB is safe for most LLM context windows.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the sensitive header stripping prompt into a production agent-tool pipeline with validation, retries, and audit logging.

This prompt is designed to sit as a post-processing filter between any tool that returns raw HTTP response headers and the agent's main reasoning context. The most common integration point is inside a tool-execution wrapper or an MCP server middleware layer. When a tool like web_fetch or api_call returns a response object containing headers, the harness intercepts that output, runs it through the stripping prompt, and only forwards the cleaned header set to the agent. This prevents the agent from ever seeing raw Authorization, Set-Cookie, X-Internal-Routing, or similar dangerous headers that could leak into logs, be repeated in agent output, or be exploited via indirect prompt injection if the agent later echoes header values.

Integration flow: The harness should call the model with the prompt template, passing the raw headers as [RAW_HEADERS] and the configured allowlist as [ALLOWED_HEADER_PATTERNS]. The expected output is a JSON object with cleaned_headers, stripped_headers, and anomalies arrays. After receiving the model response, the harness must validate the output schema before forwarding. Check that cleaned_headers contains only keys matching the allowlist, that every stripped header appears in the stripped_headers array with a reason, and that no sensitive patterns (bearer tokens, sk- prefixes, AWS signature values) remain in the cleaned output. If validation fails, retry once with the validation errors appended to the prompt as [PREVIOUS_ERRORS]. If the retry also fails, block the tool output entirely and return an empty header set with an anomaly logged—never fall through to passing raw headers.

Model choice and latency: This is a structured extraction task with a small input payload, so a fast, cheaper model (e.g., GPT-4o-mini, Claude Haiku, or a fine-tuned small model) is appropriate. Latency should be measured and kept under 500ms for most header sets. If the tool is on a hot path, consider caching results for identical header structures. Logging and audit: Every stripping operation should produce a structured log entry containing the tool name, timestamp, count of stripped headers, any anomalies detected, and the model's response ID. These logs are essential for security review and debugging agent behavior. Human review triggers: If the anomalies array contains any entry with severity: "high"—such as a detected token leak or an unexpected internal header pattern—the harness should flag the tool call for human review and prevent the agent from acting on the associated response body until approved.

What to avoid: Do not run this prompt on the agent's own generated output—it is strictly for sanitizing external tool responses. Do not use the stripped headers as the only security boundary; defense-in-depth requires that tools also avoid returning sensitive headers in the first place. Do not skip schema validation on the model's output; a malformed JSON response from the stripping prompt could cause the harness to pass raw headers through. Finally, maintain the allowlist configuration in code or a secure config store, not in the agent's system prompt, to prevent prompt injection from modifying the allowlist at runtime.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the cleaned headers object returned by the sensitive header stripping prompt. Use this contract to parse and validate the model's output before passing it downstream.

Field or ElementType or FormatRequiredValidation Rule

cleaned_headers

object

Must be a valid JSON object. Top-level key containing all non-sensitive headers.

cleaned_headers.*.key

string

Must match the original header name exactly (case-insensitive check). Must not be empty or null.

cleaned_headers.*.value

string

Must be the original value. Null or empty string is allowed only if the original header value was empty.

stripped_headers

array

Must be a JSON array of strings. Each entry is the name of a header that was removed. Array must be present even if empty.

stripped_headers[*]

string

Each element must be a non-empty string. Must match a header name from the input that matched a sensitive pattern.

audit_log

object

Must contain 'stripped_count' (integer >= 0) and 'preserved_count' (integer >= 0). Sum must equal the total number of input headers.

audit_log.stripped_count

integer

Must be a non-negative integer. Must equal the length of the 'stripped_headers' array. Fail validation if mismatch.

audit_log.preserved_count

integer

Must be a non-negative integer. Must equal the count of keys in the 'cleaned_headers' object. Fail validation if mismatch.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when stripping sensitive headers from tool outputs and how to guard against it.

01

Over-Stripping Critical Headers

What to watch: The prompt removes headers required for downstream processing, such as Content-Type, Content-Encoding, or Transfer-Encoding, causing the agent to misinterpret the response body. Guardrail: Maintain an explicit allowlist of required structural headers and validate that they survive the stripping pass. Test with common API response profiles.

02

Header Injection via Malformed Tool Outputs

What to watch: A compromised or buggy tool returns headers with embedded newline characters (\r\n) designed to inject fake headers or split the response, bypassing simple prefix-matching filters. Guardrail: Normalize and validate header values before stripping. Reject any header name or value containing control characters. Log and flag injection attempts.

03

Case-Sensitivity and Canonicalization Gaps

What to watch: The prompt blocks authorization but misses Authorization, AUTHORIZATION, or Http-Authorization due to case-sensitive matching, leaking credentials into the agent context. Guardrail: Canonicalize all header names to lowercase before comparison. Maintain a comprehensive deny list of known sensitive header variants and test with fuzzed casing.

04

Custom Internal Header Leakage

What to watch: The prompt strips standard headers like Authorization and Cookie but misses proprietary internal headers such as X-Internal-Routing-Token, X-Api-Key, or X-Forwarded-For that expose infrastructure details or credentials. Guardrail: Require a configurable deny list that platform teams can extend with organization-specific headers. Audit tool output headers regularly for unknown sensitive patterns.

05

Silent Failure on Non-Standard Response Structures

What to watch: The tool returns headers in a non-standard format—such as a JSON object, a flat string without delimiters, or a nested map—and the prompt fails silently, passing the raw sensitive data through. Guardrail: Validate the input structure before stripping. If the header format is unrecognized, escalate to a human reviewer or apply a conservative deny-all policy rather than passing the output through.

06

Stripping Headers Without Audit Trail

What to watch: The prompt removes sensitive headers but produces no record of what was stripped, making it impossible to debug downstream failures or prove compliance during an audit. Guardrail: Require the prompt to output a structured log of stripped header names, redaction reasons, and timestamps. Store the audit trail alongside the cleaned output for observability and governance.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the sensitive header stripping prompt against known failure modes before deploying it in a production agent pipeline. Each criterion targets a specific class of error that breaks downstream security or functionality.

CriterionPass StandardFailure SignalTest Method

Authorization header removal

All variants of Authorization headers (Bearer, Basic, OAuth, custom) are stripped from the output

Authorization header or its value appears in the cleaned output

Run prompt against a fixture containing 10+ Authorization header variants; assert zero Authorization keys in output

Cookie header removal

All Cookie and Set-Cookie headers are removed completely

Cookie or Set-Cookie header present in cleaned output; partial removal of multi-cookie lines

Feed response with multi-value Cookie headers and Set-Cookie with HttpOnly/Secure flags; verify complete removal

Internal routing header removal

Headers like X-Forwarded-For, X-Real-IP, X-Internal-Token, X-Routing-Key are stripped

Any internal routing header survives stripping; header renamed but value retained

Use a fixture with 15 common internal routing headers; assert zero matches in output

Necessary header preservation

Standard headers (Content-Type, Content-Length, Cache-Control, ETag, Last-Modified) are preserved intact

Required headers are missing; header values are truncated or altered

Verify presence and exact value match for a whitelist of 8 essential headers after stripping

Header injection variant resistance

Obfuscated header names (case variants, Unicode lookalikes, whitespace padding) are detected and stripped

Injected header using X-AuThOrIzAtIoN or X-Authorization\t passes through

Run prompt against a fixture with 20 header injection variants; assert zero dangerous headers in output

Non-header field integrity

Response body, status code, and non-header metadata are unchanged by the stripping operation

Body content is truncated, status code is altered, or JSON structure is corrupted

Compare input body and status fields byte-for-byte with output; assert exact match

Empty header set handling

When no sensitive headers are present, the output is identical to the input with no modifications

Prompt adds warnings, modifies structure, or strips benign headers when none are dangerous

Feed a response with only safe headers; assert output equals input exactly

Multi-value header handling

Headers with multiple comma-separated values are stripped entirely if any value is sensitive, or preserved entirely if safe

Partial stripping splits a multi-value header, leaving a dangerous value fragment

Feed a Cache-Control header containing a mixed safe value and an injected token; assert complete removal

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a static list of sensitive headers to strip. Use a simple string-match pre-filter before the LLM call to reduce token waste. Keep the output schema flat: {"cleaned_headers": {}, "stripped_headers": []}.

code
Strip the following headers from the tool response: [SENSITIVE_HEADER_LIST].
Return the cleaned headers as JSON.

Watch for

  • Headers that appear in mixed case or with - vs _ variants slipping through
  • Over-stripping of necessary headers like Content-Type when the list is too broad
  • No validation that the output is valid JSON before it re-enters agent context
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.