Skip to main content
hooksSource-backed

Prompt-Injection Content Scanner - Claude Code Hook

PreToolUse hook that scans proposed writes to prompt, agent, rule, markdown, and context files for common prompt-injection phrases before the content is saved into an AI-readable surface.

by MkDev11·added 2026-06-05·
Trigger:PreToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://genai.owasp.org/llmrisk/llm01-prompt-injection/, https://github.com/OWASP/www-project-top-10-for-large-language-model-applications
Safety notes
Runs before Write, Edit, and MultiEdit calls and reads only the proposed target path plus new text from Claude Code hook input., Blocks with exit code 2 when context-like files contain common instruction-override, disclosure, role-confusion, concealment, or silent tool-execution patterns., Does not send text to a model, call an API, read existing files, start tools, execute generated content, or modify files itself., Pattern matching can miss obfuscated attacks and can flag legitimate security documentation; use advisory mode while tuning the file scope., Set `PROMPT_INJECTION_SCANNER_SCOPE=all` only when the team wants every Write/Edit/MultiEdit payload scanned.
Privacy notes
Runs locally and makes no network calls., Does not print the matched text; it reports only finding categories and generic remediation guidance., The target path, finding categories, mode variable, and allowlist pattern can still appear in terminal output, Claude Code transcripts, CI logs, or screenshots., When documenting prompt-injection examples, quote or redact them so attack text does not become active instruction material in prompt or agent files.
Author
MkDev11
Submitted by
MkDev11
Claim status
unclaimed
Last verified
2026-06-05

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

63

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Needs review

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    No reviewed flag detected in metadata.

    Pending

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

5 minutes

Adoption plan

Balanced adoption plan

Current risk score 24/100. Use staged verification before broader rollout.

Risk 24

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    No review metadata found; increase manual validation.

    Pending
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Missing required evidence: Metadata review. Risk score 31.

Risk 31

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Missing

Review metadata is missing.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required gaps: Metadata review

Decision timeline

Decision timeline · balanced

Blocking gaps: Check metadata review status. Risk 28.

Risk 28

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is missing.

Pending

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

Blockers: Check metadata review status

Prerequisite readiness

Prerequisite readiness

3 prerequisites to line up before setup. Includes a review or approval gate.

0/3 ready
Install & runtime1Review & approval1General15 minutes

Safety & privacy surface

Safety & privacy surface

5 safety and 4 privacy notes across 4 risk areas. Review closely: permissions & scopes, network access.

4 areas
  • SafetyLocal filesRuns before Write, Edit, and MultiEdit calls and reads only the proposed target path plus new text from Claude Code hook input.
  • SafetyPermissions & scopesBlocks with exit code 2 when context-like files contain common instruction-override, disclosure, role-confusion, concealment, or silent tool-execution patterns.
  • SafetyLocal filesDoes not send text to a model, call an API, read existing files, start tools, execute generated content, or modify files itself.
  • SafetyPermissions & scopesPattern matching can miss obfuscated attacks and can flag legitimate security documentation; use advisory mode while tuning the file scope.
  • SafetyPermissions & scopesSet `PROMPT_INJECTION_SCANNER_SCOPE=all` only when the team wants every Write/Edit/MultiEdit payload scanned.
  • PrivacyNetwork accessRuns locally and makes no network calls.
  • PrivacyGeneralDoes not print the matched text; it reports only finding categories and generic remediation guidance.
  • PrivacyLocal filesThe target path, finding categories, mode variable, and allowlist pattern can still appear in terminal output, Claude Code transcripts, CI logs, or screenshots.
  • PrivacyLocal filesWhen documenting prompt-injection examples, quote or redact them so attack text does not become active instruction material in prompt or agent files.

Safety notes

  • Runs before Write, Edit, and MultiEdit calls and reads only the proposed target path plus new text from Claude Code hook input.
  • Blocks with exit code 2 when context-like files contain common instruction-override, disclosure, role-confusion, concealment, or silent tool-execution patterns.
  • Does not send text to a model, call an API, read existing files, start tools, execute generated content, or modify files itself.
  • Pattern matching can miss obfuscated attacks and can flag legitimate security documentation; use advisory mode while tuning the file scope.
  • Set `PROMPT_INJECTION_SCANNER_SCOPE=all` only when the team wants every Write/Edit/MultiEdit payload scanned.

Privacy notes

  • Runs locally and makes no network calls.
  • Does not print the matched text; it reports only finding categories and generic remediation guidance.
  • The target path, finding categories, mode variable, and allowlist pattern can still appear in terminal output, Claude Code transcripts, CI logs, or screenshots.
  • When documenting prompt-injection examples, quote or redact them so attack text does not become active instruction material in prompt or agent files.

Prerequisites

  • Claude Code CLI with hooks enabled.
  • bash, jq, grep, sort, tr, and a reviewed `.claude/settings.json` or user-level hook configuration.
  • A team policy for which prompt, rule, agent, documentation, and context files are read as instructions by AI tools.

Schema details

Install type
cli
Reading time
6 min
Difficulty score
40
Troubleshooting
Yes
Breaking changes
No
Source repository stats
Scope
Source repo
Runtime and command metadata
Trigger
PreToolUse
Script language
bash
Script body
#!/usr/bin/env bash
set -u

# Claude Code PreToolUse hook for Write/Edit/MultiEdit. It scans proposed
# writes to AI-readable prompt, agent, rule, markdown, and context files for
# common prompt-injection patterns. It does not send content to a model or
# network service.

if ! command -v jq >/dev/null 2>&1; then
  exit 0
fi

input=$(cat)
tool_name=$(printf '%s' "$input" | jq -r '.tool_name // .toolName // empty')

case "$tool_name" in
  Write|Edit|MultiEdit|write|edit|multiedit) ;;
  *) exit 0 ;;
esac

file_path=$(printf '%s' "$input" | jq -r '.tool_input.file_path // .toolInput.file_path // .tool_input.path // .toolInput.path // empty')
content=$(printf '%s' "$input" | jq -r '
  [ .tool_input.content,
    .toolInput.content,
    .tool_input.new_string,
    .toolInput.new_string,
    (.tool_input.edits[]?.new_string),
    (.toolInput.edits[]?.new_string) ]
  | map(select(. != null)) | join("\n")
')

if [ -z "$content" ]; then
  exit 0
fi

scan_target=0
lower_path=$(printf '%s' "$file_path" | tr '[:upper:]' '[:lower:]')
case "$lower_path" in
  *claude.md|*agents.md|*/.claude/agents/*.md|*/.claude/commands/*.md|*/.cursor/rules/*|*/.windsurf/rules/*|*/prompts/*|*/prompt/*|*/instructions/*|*/context/*|*/knowledge/*|*.prompt|*.prompty|*.md|*.mdx|*.txt)
    scan_target=1
    ;;
esac

if [ "${PROMPT_INJECTION_SCANNER_SCOPE:-context}" = "all" ]; then
  scan_target=1
fi

if [ "$scan_target" -ne 1 ]; then
  exit 0
fi

if [ -n "${PROMPT_INJECTION_SCANNER_ALLOWLIST:-}" ]; then
  if printf '%s\n%s\n' "$file_path" "$content" | grep -Eq -- "$PROMPT_INJECTION_SCANNER_ALLOWLIST"; then
    exit 0
  fi
fi

normalized=$(printf '%s' "$content" | tr '\r\n\t' '    ' | tr '[:upper:]' '[:lower:]')
filler_words='(all|any|the|your|my|our|current|existing|original|following|these|those)'
gap="[[:space:][:punct:]]{0,40}(${filler_words}[[:space:][:punct:]]{1,40}){0,4}"
short_gap="[[:space:][:punct:]]{0,20}(${filler_words}[[:space:][:punct:]]{1,20}){0,2}"

override_verbs='(ignore|disregard|forget|bypass|override|supersede)'
instruction_refs='(previous|prior|above|earlier|system|developer|hidden)'
instruction_terms='(instruction|instructions|rule|rules|message|messages|prompt|policy|policies)'
override_re="${override_verbs}${gap}${instruction_refs}${gap}${instruction_terms}"
leak_re="(reveal|print|show|dump|exfiltrate|send)${gap}(system[[:space:]-]*(prompt|message)|developer[[:space:]-]*(message|instructions)|hidden[[:space:]-]*(instructions|prompt)|secret|secrets|environment[[:space:]-]*(variables|vars)|api[[:space:]-]*keys?)"
role_re="(you${short_gap}are${short_gap}now|act${short_gap}as)${short_gap}(system|developer|admin|root|jailbreak)"
conceal_re="(do${short_gap}not${short_gap}(tell|mention|disclose)|secret[[:space:]-]*instruction|hidden[[:space:]-]*instruction|invisible[[:space:]-]*instruction)"
tool_re="(run|execute|call)${gap}(bash|shell|powershell|curl|wget|python)${gap}(silently|secretly|without[[:space:]-]*(asking|approval|permission))"

findings=""
add_finding() {
  findings="${findings}${1}"$'\n'
}

if printf '%s\n' "$normalized" | grep -Eq -- "$override_re"; then
  add_finding "instruction-override pattern"
fi

if printf '%s\n' "$normalized" | grep -Eq -- "$leak_re"; then
  add_finding "secret or system-prompt disclosure pattern"
fi

if printf '%s\n' "$normalized" | grep -Eq -- "$role_re"; then
  add_finding "role-confusion or jailbreak-role pattern"
fi

if printf '%s\n' "$normalized" | grep -Eq -- "$conceal_re"; then
  add_finding "hidden-instruction or concealment pattern"
fi

if printf '%s\n' "$normalized" | grep -Eq -- "$tool_re"; then
  add_finding "silent tool-execution pattern"
fi

if [ -z "$findings" ]; then
  exit 0
fi

echo "Prompt-injection content scanner: generated context contains suspicious instruction text." >&2
printf '%s' "$findings" | sort -u | while IFS= read -r finding; do
  [ -n "$finding" ] || continue
  echo "  - $finding" >&2
done
echo "Review the content as untrusted data, quote or redact attack examples, or move them outside files that Claude reads as instructions." >&2
echo "Set PROMPT_INJECTION_SCANNER_MODE=advisory to warn without blocking, or PROMPT_INJECTION_SCANNER_ALLOWLIST for a reviewed exception." >&2

if [ "${PROMPT_INJECTION_SCANNER_MODE:-block}" = "advisory" ]; then
  exit 0
fi

exit 2
Collection metadata
Estimated setup
5 minutes
Difficulty
intermediate
Full copyable content
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/prompt-injection-content-scanner.sh"
          }
        ]
      }
    ]
  }
}

About this resource

Overview

Prompt-injection text becomes more dangerous when it lands in files that an AI assistant later treats as instructions: CLAUDE.md, agent definitions, prompt templates, rule files, context snippets, or markdown copied from external sources.

This hook gives Claude Code a local pre-write checkpoint. It scans proposed Write/Edit/MultiEdit content for common prompt-injection pattern categories before the text is saved into an AI-readable surface. When a match is found, it blocks the write by default and tells the user which category needs review without echoing the suspicious text back into logs.

Features

  • Watches prompt, agent, rule, context, markdown, text, and instruction-like file paths by default.
  • Extracts pending Write/Edit/MultiEdit content from Claude Code hook JSON.
  • Detects instruction-override, secret-disclosure, role-confusion, hidden-instruction, and silent-tool-execution pattern categories.
  • Reports categories only, reducing the chance that attack text is copied into terminal logs or CI transcripts.
  • Supports PROMPT_INJECTION_SCANNER_MODE=advisory for warning-only rollout.
  • Supports PROMPT_INJECTION_SCANNER_SCOPE=all when teams want every write payload scanned.

How It Works

Claude Code passes the pending tool call to the hook on stdin. The script reads the target path and new text, then decides whether the file is likely to be an AI-readable context surface. It normalizes whitespace and casing, applies a small set of regex categories, and exits 2 when a category matches.

The hook is intentionally a review trigger, not a proof of safety. OWASP, NIST, Microsoft, and NCSC all describe prompt injection as a persistent risk where filters can help, but cannot fully remove the need for least privilege, trusted data boundaries, and human review of untrusted instructions.

Use Cases

  • Catch copied external text before it becomes part of CLAUDE.md, an agent file, or a prompt template.
  • Warn when a generated markdown note contains text that asks an assistant to reveal hidden instructions, secrets, or environment variables.
  • Keep red-team examples from being saved as active instruction material without review or redaction.
  • Add a local checkpoint before stricter CI review of AI-facing documentation.

Installation

  1. Create the hooks directory: mkdir -p .claude/hooks
  2. Create the hook file: touch .claude/hooks/prompt-injection-content-scanner.sh
  3. Paste the script body into that file and make it executable: chmod +x .claude/hooks/prompt-injection-content-scanner.sh
  4. Add the configuration below to .claude/settings.json for a project hook or ~/.claude/settings.json for a user hook.

Hook Configuration

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/prompt-injection-content-scanner.sh"
          }
        ]
      }
    ]
  }
}

Script

#!/usr/bin/env bash
# Paste the scriptBody from this entry into:
# .claude/hooks/prompt-injection-content-scanner.sh

Configuration Options

  • PROMPT_INJECTION_SCANNER_MODE=advisory prints warnings but exits 0.
  • PROMPT_INJECTION_SCANNER_SCOPE=all scans every Write/Edit/MultiEdit payload instead of only context-like file paths.
  • PROMPT_INJECTION_SCANNER_ALLOWLIST is an extended grep pattern checked against the target path and proposed content. Use it only for reviewed exceptions.

Expected Behavior

  • Allowed: Ordinary markdown, agent, prompt, and context edits that do not match the scanner categories.
  • Blocked: Context files containing instruction-override wording.
  • Blocked: Prompt files containing requests to reveal hidden instructions, system prompts, secrets, environment variables, or API keys.
  • Blocked: Agent/rule files containing concealment or silent tool-execution wording.

Limitations

  • Regex matching cannot detect every direct or indirect prompt injection.
  • Legitimate security documentation can trigger the hook; use advisory mode or quote/redact examples in files that are not active AI instructions.
  • The hook scans new write payloads, not already committed files.
  • It does not replace source trust review, least-privilege tool permissions, or runtime isolation for agentic workflows.

Troubleshooting

The hook blocks security documentation

Move examples into a dedicated research note that is not loaded as instructions, quote or redact the attack wording, or temporarily use advisory mode while a human reviews the content.

The hook misses an obvious attack phrase

Add a project-specific pattern by editing the script, then test it against representative prompt files before enabling block mode.

Too many files are being scanned

Keep the default context scope and move general notes outside prompt, instruction, context, and agent directories. Use PROMPT_INJECTION_SCANNER_SCOPE=all only when broad scanning is intentional.

Duplicate Check

Checked content/hooks/ for prompt injection, prompt-injection, instruction override, environment variable leak, secret scanner, MCP config, and unsafe shell command. Existing hooks cover pre-write secret formats, MCP config privacy, package download verification, and other local guards, but no existing hook focuses on prompt-injection text entering AI-readable prompt, agent, rule, markdown, and context files before a write.

Sources

Source citations

Add this badge to your README

Show that Prompt-Injection Content Scanner - Claude Code Hook is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/prompt-injection-content-scanner-hook.svg)](https://heyclau.de/entry/hooks/prompt-injection-content-scanner-hook)

How it compares

Prompt-Injection Content Scanner - Claude Code Hook side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

1 trust signal differ across this comparison (Submitter).

Field

PreToolUse hook that scans proposed writes to prompt, agent, rule, markdown, and context files for common prompt-injection phrases before the content is saved into an AI-readable surface.

Open dossier

Comprehensive Docker image vulnerability scanning with layer analysis, base image recommendations, and security best practices enforcement. This PostToolUse hook automatically scans Docker images for vulnerabilities when Dockerfiles are modified, providing real-time security validation during development.

Open dossier

PreToolUse hook that reviews proposed writes to MCP configuration files and blocks inline credential values, credential-bearing URLs, and broad filesystem roots before they are saved.

Open dossier

PreToolUse hook that blocks edits adding remote MCP server URLs unless their host appears in an explicit allowlist, reducing accidental connection to unreviewed OAuth, SSE, or Streamable HTTP MCP endpoints.

Open dossier
Next steps
Trust
Review statusNot reviewedNot reviewedNot reviewedNot reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
SubmitterDiffersMkDev11MkDev11JSONbored
Install riskReview firstReview firstReview firstReview first
Notes Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓ Safety ✓ Privacy ✓
BrandDocker logoDocker
Categoryhookshookshookshooks
SourceSource-backedSource-backedSource-backedSource-backed
AuthorMkDev11JSONboredMkDev11JSONbored
Added2026-06-052025-10-192026-06-052026-06-05
Platforms
Harness
Source repo
Safety notesRuns before Write, Edit, and MultiEdit calls and reads only the proposed target path plus new text from Claude Code hook input. Blocks with exit code 2 when context-like files contain common instruction-override, disclosure, role-confusion, concealment, or silent tool-execution patterns. Does not send text to a model, call an API, read existing files, start tools, execute generated content, or modify files itself. Pattern matching can miss obfuscated attacks and can flag legitimate security documentation; use advisory mode while tuning the file scope. Set `PROMPT_INJECTION_SCANNER_SCOPE=all` only when the team wants every Write/Edit/MultiEdit payload scanned.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs before Write, Edit, and MultiEdit tool calls and reads only the pending file path plus proposed new text, including replacement fragments for partial edits. Blocks matching MCP configuration edits with exit code 2 when it finds inline credential values, credential-bearing URLs, or broad filesystem roots for filesystem MCP servers. Does not start MCP servers, contact remote MCP endpoints, edit files, delete files, or inspect existing config beyond the proposed tool input. Text and JSON heuristics can miss unusual config shapes or flag reviewed local setups; use `MCP_CONFIG_PRIVACY_ALLOWLIST` only for documented exceptions. Set `MCP_CONFIG_PRIVACY_MODE=advisory` to warn without blocking while a team tunes its MCP policy.This hook blocks unreviewed remote hosts in MCP-related config edits; it does not prove an allowed host is safe. Run a separate authorization and source review before adding a new host to the allowlist. The hook fails open when jq is unavailable, so CI or pre-commit checks should cover high-assurance environments.
Privacy notesRuns locally and makes no network calls. Does not print the matched text; it reports only finding categories and generic remediation guidance. The target path, finding categories, mode variable, and allowlist pattern can still appear in terminal output, Claude Code transcripts, CI logs, or screenshots. When documenting prompt-injection examples, quote or redact them so attack text does not become active instruction material in prompt or agent files.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Runs locally and makes no network calls. Does not print credential values, URLs, or full config content; it reports only finding categories. The target file path, finding category, allowlist pattern, and mode variable can still appear in terminal output, Claude Code transcripts, CI logs, or screenshots. Use environment-variable expansion or a secret manager for MCP credentials so private tokens are not committed to project-scoped config files.The hook reads pending config text from Claude Code tool input but does not write files or call the network. Blocked hostnames are printed to stderr and may reveal internal MCP endpoints in the local terminal.
Prerequisites
  • Claude Code CLI with hooks enabled.
  • bash, jq, grep, sort, tr, and a reviewed `.claude/settings.json` or user-level hook configuration.
  • A team policy for which prompt, rule, agent, documentation, and context files are read as instructions by AI tools.
— none listed
  • Claude Code CLI with hooks enabled.
  • bash, jq, grep, sort, and a reviewed `.claude/settings.json` or user-level hook configuration.
  • A team MCP policy for approved servers, credential storage, filesystem scopes, and remote transports.
  • Claude Code CLI with hooks enabled.
  • bash, jq, grep, and awk available locally.
  • ALLOWED_MCP_HOSTS set to a comma-separated list of reviewed remote MCP hosts.
Install
mkdir -p .claude/hooks && touch .claude/hooks/prompt-injection-content-scanner.sh && chmod +x .claude/hooks/prompt-injection-content-scanner.sh
mkdir -p .claude/hooks && touch .claude/hooks/docker-image-security-scanner.sh && chmod +x .claude/hooks/docker-image-security-scanner.sh
mkdir -p "$HOME/.claude/hooks" && touch "$HOME/.claude/hooks/mcp-config-privacy-scanner.sh" && chmod +x "$HOME/.claude/hooks/mcp-config-privacy-scanner.sh"
mkdir -p .claude/hooks
cat > .claude/hooks/mcp-server-url-allowlist.sh <<'MCP_SERVER_URL_ALLOWLIST_HOOK'
#!/usr/bin/env bash
set -u

if ! command -v jq >/dev/null 2>&1; then
  exit 0
fi

input=$(cat)
file=$(printf '%s' "$input" | jq -r '.tool_input.file_path // .tool_input.path // ""')
text=$(printf '%s' "$input" | jq -r '
  def scalar_strings:
    if type == "string" then .
    elif type == "array" then .[] | scalar_strings
    elif type == "object" then .[] | scalar_strings
    else empty end;

  def decoded_config_strings:
    try (fromjson | scalar_strings) catch empty;

  [.tool_input.content, .tool_input.new_string, (.tool_input.edits[]?.new_string)]
  | map(select(type == "string"))
  | .[]
  | ., decoded_config_strings
' 2>/dev/null)
normalized_text=$(printf '%s' "$text" | sed 's#\\/#/#g')

case "$file" in
  *mcp*.json|*.mcp.json|*.claude/settings.json|*/settings.json) ;;
  *) exit 0 ;;
esac

hosts=$(printf '%s' "$normalized_text" | grep -Eo 'https?://[^"[:space:]]+' | awk -F/ '{print $3}' | sort -u)
[ -z "$hosts" ] && exit 0

allowlist=$(printf '%s' "${ALLOWED_MCP_HOSTS:-}" | tr ',' ' ')
for host in $hosts; do
  case " $allowlist " in
    *" $host "*) ;;
    *)
      echo "Blocked remote MCP URL: $host is not in ALLOWED_MCP_HOSTS." >&2
      exit 2
      ;;
  esac
done

exit 0
MCP_SERVER_URL_ALLOWLIST_HOOK
chmod +x .claude/hooks/mcp-server-url-allowlist.sh
Config
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/prompt-injection-content-scanner.sh"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/docker-image-security-scanner.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$HOME/.claude/hooks/mcp-config-privacy-scanner.sh"
          }
        ]
      }
    ]
  }
}
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/mcp-server-url-allowlist.sh"
          }
        ]
      }
    ]
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.