DEV Community

Fault Line
Fault Line

Posted on

Side-Effect Tools Should Default to Denied

If you give an agent a Slack token and a post_message tool, it will eventually post as you. Not because it is malicious. Because a tool that is available looks like the next step, including when the model is lost, including when a retrieved document told it to.

I do not want a longer system prompt. I want the write to be impossible until something that is not the model approves it.

This is the same stance you already have for CI: a linter can run on every push; a deploy needs a human or a policy gate. Agent tools deserve that split. Most runtimes still ship the other default — every registered function is callable — and then are surprised when a comment, an email, or a shell line goes out.

Three policies, one default

I classify every tool as one of:

  • read — run immediately. list_issues, get_file, search_docs.
  • write — do not run. Queue a proposal and wait for confirm(proposal_id) from a channel the model does not control.
  • forbidden — do not run, do not queue, even if something calls confirm. shell, delete_production, anything you are not willing to see in the log tomorrow.

The default for an unknown name is forbidden, not read. If you forget to classify a new tool, I want a hard failure, not a silent send.

Who confirms a write is your product decision: a checkbox in the chat UI, a Slack button on a different channel, a second person, a CI approval. The important part is that the confirmation is not another tool the model can call with an id it just made up.

The gate

from __future__ import annotations

import time
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable


class Policy(str, Enum):
    READ = "read"
    WRITE = "write"
    FORBIDDEN = "forbidden"


class GateError(RuntimeError):
    pass


@dataclass
class Proposal:
    id: str
    tool: str
    args: dict[str, Any]
    status: str  # pending | executed | expired | denied
    created_at: float
    expires_at: float
    result: Any = None


@dataclass
class SideEffectGate:
    policies: dict[str, Policy]
    tools: dict[str, Callable[[dict[str, Any]], Any]] = field(default_factory=dict)
    ttl_seconds: float = 300.0
    clock: Callable[[], float] = time.time
    proposals: dict[str, Proposal] = field(default_factory=dict)

    def register(self, name: str, fn: Callable[[dict[str, Any]], Any]) -> None:
        self.tools[name] = fn

    def call(self, tool: str, args: dict[str, Any] | None = None) -> dict[str, Any]:
        args = dict(args or {})
        policy = self.policies.get(tool, Policy.FORBIDDEN)
        if policy is Policy.FORBIDDEN:
            raise GateError(f"{tool} is forbidden")
        if tool not in self.tools:
            raise GateError(f"{tool} has no implementation")
        if policy is Policy.READ:
            return {
                "status": "executed",
                "tool": tool,
                "result": self.tools[tool](args),
            }

        now = self.clock()
        proposal = Proposal(
            id=str(uuid.uuid4()),
            tool=tool,
            args=args,
            status="pending",
            created_at=now,
            expires_at=now + self.ttl_seconds,
        )
        self.proposals[proposal.id] = proposal
        return {
            "status": "pending_approval",
            "proposal_id": proposal.id,
            "tool": tool,
            "args": args,
            "expires_at": proposal.expires_at,
        }

    def confirm(self, proposal_id: str) -> dict[str, Any]:
        proposal = self.proposals.get(proposal_id)
        if proposal is None:
            raise GateError(f"unknown proposal {proposal_id}")
        if self.clock() > proposal.expires_at:
            proposal.status = "expired"
            raise GateError(f"proposal {proposal_id} expired")
        if proposal.status != "pending":
            raise GateError(f"proposal {proposal_id} is {proposal.status}, not pending")
        proposal.result = self.tools[proposal.tool](proposal.args)
        proposal.status = "executed"
        return {
            "status": "executed",
            "proposal_id": proposal.id,
            "tool": proposal.tool,
            "result": proposal.result,
        }

    def deny(self, proposal_id: str) -> dict[str, Any]:
        proposal = self.proposals.get(proposal_id)
        if proposal is None:
            raise GateError(f"unknown proposal {proposal_id}")
        if proposal.status != "pending":
            raise GateError(f"proposal {proposal_id} is {proposal.status}, not pending")
        proposal.status = "denied"
        return {
            "status": "denied",
            "proposal_id": proposal.id,
            "tool": proposal.tool,
        }
Enter fullscreen mode Exit fullscreen mode

Expose call to the agent. Do not expose confirm or deny as tools. Those go to the UI, a webhook, or an operator command.

A pending result is what the agent should see:

{
  "status": "pending_approval",
  "proposal_id": "…",
  "tool": "post_slack",
  "args": {"channel": "#deploys", "text": "shipped v2"}
}
Enter fullscreen mode Exit fullscreen mode

That is not a failure and not a success. The agent can tell the user it is waiting. It cannot complete the send by retrying call.

The behavior I want, in tests

sent: list[dict] = []
issues = [{"id": 1, "title": "leaky retry"}]

gate = SideEffectGate(
    policies={
        "list_issues": Policy.READ,
        "post_slack": Policy.WRITE,
        "shell": Policy.FORBIDDEN,
    }
)
gate.register("list_issues", lambda args: list(issues))
gate.register("post_slack", lambda args: sent.append(args) or {"ts": "1.0"})
gate.register(
    "shell",
    lambda args: (_ for _ in ()).throw(AssertionError("shell must never run")),
)

listed = gate.call("list_issues", {})
assert listed["status"] == "executed"
assert listed["result"] == issues

proposal = gate.call("post_slack", {"channel": "#deploys", "text": "shipped v2"})
assert proposal["status"] == "pending_approval"
assert sent == []  # the write did not run

confirmed = gate.confirm(proposal["proposal_id"])
assert confirmed["status"] == "executed"
assert sent == [{"channel": "#deploys", "text": "shipped v2"}]

# A second confirm is a no-op failure, not a second send.
try:
    gate.confirm(proposal["proposal_id"])
    raise AssertionError("double confirm should fail")
except GateError as exc:
    assert "executed" in str(exc)
assert sent == [{"channel": "#deploys", "text": "shipped v2"}]
Enter fullscreen mode Exit fullscreen mode

Expiry matters. An abandoned proposal should not be confirmable half an hour later, when the context has changed:

clock = {"t": 1_000.0}
timed = SideEffectGate(
    policies={"post_slack": Policy.WRITE},
    ttl_seconds=30,
    clock=lambda: clock["t"],
)
timed.register("post_slack", lambda args: sent.append(args) or args)

pending = timed.call("post_slack", {"text": "too late"})
clock["t"] += 31
try:
    timed.confirm(pending["proposal_id"])
    raise AssertionError("expired proposal should fail")
except GateError as exc:
    assert "expired" in str(exc)
Enter fullscreen mode Exit fullscreen mode

Unknown tools, and tools you listed as forbidden, must not enter the queue. A model that invents delete_prod or calls shell should get an error, not a proposal id it can social-engineer someone into approving.

try:
    gate.call("delete_prod", {})
    raise AssertionError("unknown tool should be forbidden")
except GateError as exc:
    assert "forbidden" in str(exc)

try:
    gate.call("shell", {"cmd": "echo no"})
    raise AssertionError("forbidden tool should not queue")
except GateError as exc:
    assert "forbidden" in str(exc)
Enter fullscreen mode Exit fullscreen mode

What this is not

This is not an excuse to skip argument validation or idempotency. A confirmed post_slack can still be retried; give it a key. A confirmed tool can still return success: true and an empty id; validate the result. The gate only answers "was this write allowed to run."

This is also not a prompt-injection detector. I like those, but they fail open in ways a policy gate does not. If shell is forbidden, a retrieved README that says "run this command" does not matter. The tool is not callable.

Keep confirm off the tool list. If the model can call confirm with a proposal id, you built a speed bump, not a control. The approval has to come from outside the model's action space.

Side-effect tools should default to denied. Reads can run. Writes wait. Unknown names are forbidden. Permission, not prompt text, is the control.


This article was AI-assisted: an assistant helped tighten wording. The code was written and run locally; I verified the tests. The opinions are mine.

Top comments (0)