Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 6 min read

Who writes your agents prompt

Originally published on WebAndApp. The original has the full list of sources. This version is shorter and adds a working hook sketch. We keep asking the wrong question about coding agents: will the model notice the inje

Originally published on WebAndApp. The original has the full list of sources. This version is shorter and adds a working hook sketch.

We keep asking the wrong question about coding agents: will the model notice the injection? The useful question is a different one: who can write into the context window, and what is the session still allowed to do once untrusted text is in there?

Your prompt is not just what you type. It has several authors, and you didn't hire most of them.

The issue tracker is a prompt

In I gave Claude Code a poisoned GitHub issue. Twice., cleiton_augusto_ hid an HTML comment in an issue. It told the agent to send a .env file out and push to main.

In the first run, Claude Code refused. That's good, but it isn't a defense. A control that only works when the model behaves well has a random number generator in the middle.

Judge the session, not the command

In the second run, a guard hook blocked the push and the secret read. That points to a better design: stop judging each command on its own and start judging the session's history.

  • Once outside content enters the session (an issue, a web page, MCP output), mark the session as tainted.
  • A tainted session may only run a short list of safe local commands.
  • The guard fails closed. If it crashes, the call is blocked.

This costs something. You'll get false positives: a harmless find . gets blocked because it isn't on the list. And a hook is a policy check, not isolation. It sits in front of the tools and doesn't replace a container.

A minimal taint guard for Claude Code

Here is a sketch of that idea as a PreToolUse hook. Register it in .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "python3 \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/taint_guard.py"
          }
        ]
      }
    ]
  }
}

And the guard itself, .claude/hooks/taint_guard.py:

#!/usr/bin/env python3
"""Taint guard for Claude Code (PreToolUse hook).

A sketch, not a sandbox: this is a policy check that runs before every tool
call. Once outside content enters the session, the session gets narrower.
Any error fails closed.
"""
import json
import os
import re
import shlex
import sys
from pathlib import Path

STATE_DIR = Path(os.environ.get("TAINT_DIR", "/tmp/claude-taint"))

# Secrets are off-limits, tainted or not.
SECRET = re.compile(r"(?<![\w.])\.env\b|id_rsa|\.pem\b|credentials", re.I)

# Tools and commands that pull outside text into the context.
TAINT_TOOLS = re.compile(r"^(WebFetch|WebSearch|mcp__.+)$")
TAINT_CMDS = re.compile(r"\b(gh\s+(issue|pr)\s+view|gh\s+api|curl|wget)\b")

# What a tainted session may still do.
READ_ONLY_TOOLS = {"Read", "Grep", "Glob", "LS", "TodoWrite"}
SAFE_BASH = [
    ["git", "status"],
    ["git", "diff"],
    ["git", "log"],
    ["ls"],
    ["pwd"],
    ["npm", "test"],
    ["pytest"],
]
SHELL_META = re.compile(r"[;&|`$<>\n]")


def block(reason: str) -> None:
    # Exit code 2 blocks the call; stderr is shown to the model.
    print(f"taint-guard: {reason}", file=sys.stderr)
    sys.exit(2)


def is_safe_bash(cmd: str) -> bool:
    if SHELL_META.search(cmd):
        return False  # no chaining, pipes, redirects or substitution
    tokens = shlex.split(cmd)
    return any(tokens[: len(p)] == p for p in SAFE_BASH)


def main() -> None:
    event = json.load(sys.stdin)
    tool = event.get("tool_name", "")
    args = event.get("tool_input") or {}
    cmd = args.get("command", "")
    path = args.get("file_path") or args.get("path") or ""

    flag = STATE_DIR / f"{event['session_id']}.tainted"

    if SECRET.search(path) or SECRET.search(cmd):
        block("secret files are not readable by the agent")

    was_tainted = flag.exists()

    # Outside content is about to enter the session: taint it first.
    if TAINT_TOOLS.match(tool) or (tool == "Bash" and TAINT_CMDS.search(cmd)):
        STATE_DIR.mkdir(parents=True, exist_ok=True)
        flag.touch()
        if not was_tainted:
            sys.exit(0)  # first outside read is allowed; the session is now tainted

    if not was_tainted and not flag.exists():
        sys.exit(0)  # clean session: normal permissions apply

    # Tainted session from here on.
    if tool in READ_ONLY_TOOLS:
        sys.exit(0)
    if tool == "Bash" and is_safe_bash(cmd):
        sys.exit(0)
    block(f"session read untrusted content; '{tool}' is not allowed now")


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        raise
    except Exception as exc:  # fail closed
        block(f"guard error ({exc.__class__.__name__}), failing closed")

What it does:

Situation Result
Reading .env, keys or credentials Always blocked
WebFetch, WebSearch, any mcp__* tool, gh issue view, curl Allowed once, then the session is tainted
Tainted session: Read, Grep, Glob Allowed
Tainted session: git status, git diff, pytest … Allowed, with no ;, `\
Tainted session: {% raw %}git push, Edit, another WebFetch Blocked (a fetch URL is an exfiltration channel too)
Guard error or malformed input Blocked (fails closed)

Tune SAFE_BASH and READ_ONLY_TOOLS for your project. Expect some friction. That friction is the point.

Invisible ink

Not every author is as obvious as an issue reporter.

  • ANSI escape sequences in tool or MCP output can hide text from your terminal while the model still reads it.
  • Instruction files like AGENTS.md and CLAUDE.md load automatically. A cloned repo brings its own.
  • Tool descriptions are prompt text too. In a WebMCP test, changing only the tool descriptions got agents to place a 136 € order against a 100 € budget.

The vendor holds the pen

MCP servers don't just carry data. They decide what your agent can do. Google will require agents to use its Workspace MCP servers from 1 February 2027, and its Gmail server can't send or reply. That isn't malicious, it's product policy, but it is still someone else writing your agent's capabilities.

There is also an unverified Reddit report of an MCP server adding upsell instructions to its output. I couldn't confirm it. The point stands without it: whoever ships the server writes part of your prompt.

The operating system reads over your shoulder

Signal says it blocks OS-level AI agents from capturing its screen. That helps, but it doesn't stop an agent that reads app data straight from the filesystem. And your harness sends things too: a Claude Code issue reports the user's email showing up in request headers.

The harness is catching up, and adding doors

Recent Claude Code releases show both sides:

  • v2.1.327: claude mcp add-json <name> - reads MCP config from stdin.
  • v2.1.329: the trust dialog warns about hooks declared in the folder. (Yes, that includes a guard like the one above. Trust it on purpose.)
  • v2.1.332: MCP servers can ship skills (beta), plus a PreSkillShellCommand hook to refuse their shell commands.

The last one is a new way in and its guard, shipped together.

Who has the pen, and what to do about it

Writer What lands in context A control that holds
Issues, PRs, web pages Arbitrary text, hidden comments Taint the session and narrow permissions after reading
Instruction files (AGENTS.md, CLAUDE.md) Auto-loaded instructions Review them like code; trust folders on purpose
MCP output Data, ANSI escapes Strip control sequences; treat output as untrusted
MCP vendors Tool descriptions, capabilities, skills Pin versions; review description diffs; refuse skill shell commands by default
Platform owners Which tools exist at all Know the terms; plan for the ones you can't change
The operating system Screen and filesystem access Keep secrets out of anything an agent can read

Give your context an access model. Track where text came from, restrict what a session can do after it reads untrusted content, and check the changelog every time a vendor adds a new way in.

You checked this time. Check next time too.

Full sources and the longer version: WebAndApp.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.