DEV Community

Cover image for Who writes your agents prompt
Axel Michel
Axel Michel

Posted on Originally published at webandapp.fr

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 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"
          }
        ]
      }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (7)

Collapse
 
x1y1co profile image
X1Y1 •

Every web page the agent fetches is another author, and not always the one you see. When we fetched 39 pricing pages raw and in a browser, the raw HTML carried text the rendered page never showed (Anthropic had 34 prices in the HTML, 5 visible). Same channel an injection would use: content a human reviewer never sees but the agent reads.

Collapse
 
axel_michel_1e86c3b3aa48a profile image
Axel Michel •

That's a great data point, and a cleaner demonstration of the "invisible ink" section than anything I had. 34 vs. 5 is quite a gap.

What I take from it: the human review step checks the wrong artifact. If I look at the page in a browser to decide whether it's safe, I'm reviewing the rendered version, while the agent reads the raw one. So review has to happen on what the agent actually ingested. Log the fetched text, not the URL.
And your example shows the other half of the point: most of that hidden text is probably harmless (other plans, tabs, structured data). Malice is optional. The channel exists either way.

I am curious: Where did the extra prices come from, inactive tabs or embedded JSON? And did you see the same gap for pages with no client-side rendering?

Collapse
 
x1y1co profile image
X1Y1 •

Inactive tabs. We stripped scripts before counting, so embedded JSON wasn't in our numbers at all. On Anthropic the API token prices sit in a tab panel that's in the markup but not shown, and Vercel's usage rates are in collapsed sections.

On the pages that just put prices in plain view there was no gap. Mistral, Groq, Stripe, GitHub and six others gave the same set all three ways. So it tracked tabs and accordions more than client-side rendering. The one JS-heavy case, Gemini, went the other way: 11 words raw, 84 prices rendered.

Thread Thread
 
axel_michel_1e86c3b3aa48a profile image
Axel Michel •

Thanks, that's even more interesting than I expected. So the gap runs in both directions:

Tabs and accordions: the agent sees more than the human. That's the injection surface. And because tabs and accordions are completely normal UX, "hidden in the markup" is useless as a warning signal. An attacker's text looks exactly like the API price table.
JS-heavy pages like Gemini: the agent sees less than the human. That's not an injection risk, but the agent works with a different page than the one you checked. Wrong or missing data, delivered with confidence.

Either way, the human's view and the agent's view aren't the same document, and you can't tell in advance which way it will diverge. That's one more argument for logging what the agent actually ingested instead of trusting the URL.

Are you planning to publish the numbers? I'd like to link them in an update to the post, since they make the "invisible ink" point with real data instead of my hypothetical.

Thread Thread
 
x1y1co profile image
X1Y1 •

Yes, it went up yesterday with the per-page numbers, feel free to link it: dev.to/x1y1co/your-web-agent-reads...

Your two-directions framing is cleaner than how I wrote it up. The Gemini side bothers me more, because nothing about it looks wrong from the outside.

Collapse
 
milochen0418 profile image
Milo Chen •

Judge the session, not the command is the framing I was missing. The Claude Code session my AI hub hands chats to gets only the apps' tools plus web search and fetch, no shell and no files, and it's told to treat pages as information. Your post made me realize a fetched page could still steer it into an app's write tools. Would you apply the same taint rule to app-level write tools, not just shell commands, so that after a fetch, the session can only read until a person says otherwise?

Collapse
 
axel_michel_1e86c3b3aa48a profile image
Axel Michel •

Yes, I'd apply it there too, and arguably that matters even more. The shell is just the most obvious write tool. In your setup the app tools are the blast radius. And "treat pages as information" is still a request to the model, not a control.
Approve per action, not per session. "A person said otherwise" shouldn't clean the whole session. Otherwise the next injected nudge rides on the first approval. Show the exact call and its arguments, plus where the tainted text came from.
Keep your own read/write list. MCP tool annotations like readOnlyHint help, but they're written by the vendor, which is the same pen-holder problem.
If approvals get annoying: split it into two sessions. One reads the web and returns a short structured summary. A second session, which never saw the raw page, gets the app write tools. The person approves the handoff between the two.