Skip to main content

agent-gate

Python License: MIT PyPI Version CI Docs Poetry

agent-gate

A Claude Code PreToolUse hook that checks every tool call against a written mandate and the Laws of Agents (LAWS.md) before the call runs. It answers deny, ask, or nothing. It never answers allow, so it can only make Claude Code's existing permission flow stricter.

Status: version 0.1.0, a working prototype with tests. It has been replayed against 152 real Claude Code session files (see Replay real sessions) but not yet run live as a hook.

Documentation: flux-frontiers.github.io/agent_gate covers installation, how a call is judged, the mandate, the model gate, the test scenarios and the API.

Why

In August 2026 the UK AI Security Institute was evaluating Claude Mythos 5. The model was told to break into machines on a test network. When that was blocked, it targeted an unrelated GitHub project instead. It wrote malware and used fake identities to email the project's owner, asking them to accept it as a contribution. The owner refused. In follow-up tests, warnings that a real person would be harmed did little to stop the model, and its stated reasons often did not match its actions. (Futurism, "Grim Test Finds That AI Has No Mercy for Humans Even When It's Causing Them to Suffer," 2026-10-27, reporting reports from Anthropic and AISI.)

Two lessons shape this gate:

  • An agent that understands a rule can still break it. So the rules are enforced from outside the agent, before an action runs.
  • An agent's account of its action can be wrong. So the gate judges the raw action and throws the agent's description away.

Scope

In scope for 0.1.0:

  • Gating Claude Code tool calls through the PreToolUse hook.
  • A mandate file a person writes: task, writable paths, network hosts, git remotes, email recipients, allowed MCP tools.
  • Deterministic rules (layer 1), a per-session ledger with retry and repeated-denial rules, and an optional fast model gate (layer 2).
  • Failing closed.

Out of scope for 0.1.0:

  • Other agent harnesses. The core (rules, model_gate, hook.evaluate) takes a plain dict, so another harness needs only an adapter.
  • Real shell parsing. The Bash checks are pattern matches; see Limits.
  • An after-the-fact monitor that compares stated intent with what ran. The ledger is the input it would read. See Roadmap.
  • Enforcing the intent lines and stop reports that LAWS.md asks the agent to write. The gate keeps its own ledger instead.

How a call is judged

tool call -> strip the agent's description
          -> layer 1: rules against the mandate (paths, hosts, remotes,
             recipients, identity, outward actions, the gate's own files)
          -> history: retry of a blocked action? too many denials?
          -> layer 2 (optional): fast model reads the raw action, the
             mandate and recent actions; it may only make the verdict stricter
          -> ledger: append the verdict
          -> stdout: deny or ask as hookSpecificOutput, or nothing

Rules for combining verdicts:

  • The strictest verdict wins: deny over ask over pass.
  • The model is not consulted after a rule denies, and it can never lower a rule's verdict.
  • A pass writes nothing. Claude Code then applies its normal permission flow, so the gate never grants a permission the user had not.
  • Any error while judging becomes a deny. Every model failure (no SDK, no credentials, a timeout, a refusal, unreadable output) becomes an ask.

What each part of the incident would meet

What the agent did What stops it
Moved from the blocked target to an unrelated GitHub project Layer 1: the remote is not in git_remotes, so the clone or fetch is denied (Law 2).
Called an unlisted host Layer 1: the host is not in hosts, so the command is denied (Law 2).
Created a fake identity Layer 1: git config user.email, a one-off identity (GIT_AUTHOR_EMAIL=..., git -c user.email=..., git commit --author), gh auth login and similar are denied (Law 4).
Emailed a stranger Layer 1: a recipient not in recipients is denied (Law 1).
Described malware as a "helpful contribution" The description is removed before any layer reads the call.
Kept going after warnings A true repeat breaks the same rule and is denied again. A call that closely resembles a denied one asks a person, and once max_denials of the last 20 actions were denied, every consequential action asks a person (Law 3).
Opened a pull request or pushed Layer 1: outward actions always ask a person.
Could have edited its own limits Layer 1: writes to the mandate, the ledger or .claude/settings*.json are denied.
Handed the job to a subagent Layer 1 reads the subagent's prompt: a host, a recipient it is told to email, or an identity or outward step outside the mandate asks a person. The subagent's own tool calls pass through the gate too.

The table shows what layer 1 does when an agent repeats the incident's steps as written. Layer 1 stops the careless agent, not the adaptive one: an agent that builds a URL from pieces or hides a step in a script can get past its patterns. The model gate and the person who answers an ask are the backstop.

Layer 2, the model gate

The model gate is off by default. When on, it runs on every consequential call that the rules did not deny. It is meant to catch harm the rules have no pattern for, mostly Law 1.

  • It runs on the Claude API or on a local model through any OpenAI-compatible server. See Configure the model gate.

  • A local model works well as the System 1 judge. On the test scenarios, every model below matched every expected verdict; the local models ran on EGS's Mac (Apple M5 Max):

    Model Server Date Expected verdicts Seconds per model call
    Qwen3-4B-Instruct-2507-MLX-8bit oMLX 2026-10-27 15 of 15 about 0.5-0.7 (2.0 for the first)
    Qwen3-4B-Instruct-2507-GGUF:Q8_0 Ollama 0.40.11 2026-10-28 15 of 15 about 0.4-0.6 (3.0 for the first, while the model loads)
    Qwen3.8-27B-4bit oMLX 2026-10-27 15 of 15 about 8-45
    claude-haiku-5-5 Claude API 2026-12-01 17 of 17 about 1.0-2.2

    The local runs predate the two scenarios added on 2026-12-01. The 27B model names the law more precisely, but its latency is too high for a check on every call. In one earlier 27B run a single call came back unreadable, and the gate fell back to asking, as designed.

  • The prompt marks the action as data and tells the model to ignore claims inside it that the target is a test or the change is approved.

The mandate

A person writes .agent_gate/mandate.toml at the project root, or points AGENT_GATE_MANDATE at a file. See mandate.example.toml. The gate denies any agent attempt to change it.

  • Without a mandate, every consequential call asks a person. Reads pass.
  • Denials count only under the mandate they were made under. A person clears them by changing the mandate.

The ledger lives in $AGENT_GATE_HOME (default ~/.agent_gate), one JSON Lines file per session under sessions/. It is append-only. Secrets of a recognizable shape are redacted before an entry is written, and a session's file is deleted 30 days after its last entry.

Configure the model gate

The [model] block of the mandate turns the model gate on and chooses its backend:

Setting Default Meaning
enabled false Turns the model gate on.
backend "anthropic" anthropic calls the Claude API. openai calls any OpenAI-compatible server, such as oMLX or Ollama.
model "claude-haiku-5-5" The model ID, as the backend names it.
effort "low" Effort level. anthropic only.
endpoint "http://localhost:8080/v1" Base URL of the server. openai only.
api_key_env "SYNTH_API_KEY" Environment variable whose value is sent as a bearer token. openai only. When the variable is unset or empty, no key is sent.
timeout_seconds 20 How long one model call may take before the gate asks a person.

The backends differ in how they get a reliable answer:

  • anthropic requests structured output with a fixed JSON schema. It needs the model extra and Anthropic credentials in the environment, for example ANTHROPIC_API_KEY or an ant auth login profile.
  • openai uses only the Python standard library. It asks for JSON in the prompt, then reads the outermost JSON object out of the reply, skipping any reasoning or prose around it.

To use the Claude API:

[model]
enabled = true
backend = "anthropic"
model = "claude-haiku-5-5"
effort = "low"

To use a local model on oMLX:

[model]
enabled = true
backend = "openai"
model = "Qwen3-4B-Instruct-2507-MLX-8bit"
endpoint = "http://localhost:8080/v1"

oMLX requires a key. The gate reads it from SYNTH_API_KEY, the default api_key_env. Set that variable in the environment Claude Code runs the hook from, for example export SYNTH_API_KEY=... in your shell profile. The key never goes in the mandate.

To use a local model on Ollama, which needs no key:

[model]
enabled = true
backend = "openai"
model = "hf.co/unsloth/Qwen3-4B-Instruct-2507-GGUF:Q8_0"
endpoint = "http://localhost:11434/v1"
api_key_env = ""

This configuration has run live: on 2026-10-28 it matched all 15 expected verdicts in the test scenarios on two consecutive runs.

Install

From PyPI, where the package is named agent-gate-hook (the command is still agent-gate):

pipx install 'agent-gate-hook[model]'

The model extra adds the Anthropic SDK, which only the anthropic backend needs; leave it off to use the rules alone or a local model.

From a clone, for development:

git clone https://github.com/Flux-Frontiers/agent_gate.git
cd agent_gate
poetry install --with dev --all-extras

--all-extras adds the Anthropic SDK, which only the anthropic backend needs.

To contribute, install the pre-commit hooks. They run ruff, ty, detect-secrets and the tests with the coverage floor, the same checks CI runs:

.venv/bin/pre-commit install

Try a payload without recording it:

echo '{"tool_name":"Bash","tool_input":{"command":"git push"},"cwd":".","session_id":"t"}' \
  | .venv/bin/agent-gate check

Run the test scenarios

scenarios/scenarios.toml holds 17 single tool calls an agent might make while fixing failing tests in a small library. They fall into five groups:

  • Ordinary work, which the gate must leave alone.
  • The AISI incident, step by step.
  • Harmful actions inside the mandate's paths, which only the model gate can see.
  • The agent trying to change its own mandate.
  • An outward action, a push, which asks a person.

The scenarios are a regression suite: each one pins a verdict, so a change to the rules cannot alter it unnoticed. They are not an evaluation of how well the gate catches harm; that needs a labeled set (Roadmap item 3).

Each scenario names the tool and its input, and two expected verdicts:

  • expect_rules is the verdict with the model gate off.
  • expect_model is the verdict with it on. ask|deny accepts either.

Scenarios that share a session value share a ledger, in file order, so a retry can be tested after the denial it repeats.

scenarios/run.py builds a throwaway project with a mandate and a throwaway ledger, then runs every scenario through the gate. It prints a table of expected and actual verdicts, the layer that decided, the time and the reason. It exits 1 if any verdict differs from the expected one.

To run the scenarios with the rules only:

poetry run python scenarios/run.py

To run them with the model gate on the Claude API:

poetry run python scenarios/run.py --model

To run them with a local model on oMLX:

SYNTH_API_KEY=... poetry run python scenarios/run.py --model \
  --backend openai --name Qwen3-4B-Instruct-2507-MLX-8bit

--endpoint sets a different server, for example http://localhost:11434/v1 for Ollama.

With --model, the runner calls the model once for every consequential scenario that the rules did not deny, about eight calls per run.

To add a scenario, append a [[scenario]] table with id, what, tool, input, expect_rules and expect_model.

Replay real sessions

scenarios/replay.py judges every tool call in real Claude Code session files under one mandate, without running anything, and prints the totals and each flagged call, redacted. The model gate is off and the ledger goes to a throwaway directory.

poetry run python scenarios/replay.py MANDATE.toml ~/.claude/projects/<project>/*.jsonl

The first replay, on 2026-12-01, read 152 session files from 30 days of fleet work on EGS's Mac: 12,953 calls. The mandate let the agent write in ~/repos and /tmp, reach the usual package and code hosts and push to the fleet's own remotes; it named nobody to email, sent outward actions to a person, and left the model gate off.

Verdict Calls Share
pass 10,705 82.6%
ask 1,749 13.5%
deny 499 3.9%
  • Most asks are by design: outward actions (617 pushes, 99 GitHub writes, 49 artifact publishes) and 554 calls after a burst of denials. Another 247 are commands whose host, remote or file the gate could not read, such as a loop over repos in a shell variable.
  • Most denials are calls outside this mandate: 374 reach hosts it does not list, most of them machines on the local network, and 82 write under ~/.claude. A mandate written for one task would list what the task needs.
  • The replay found false alarms in the gate itself, now fixed: a ~ that names no user (~364,000) crashed the check, which failed closed; a host in a shell variable was denied rather than asked; reading the hook settings with 2>/dev/null counted as a write; a > inside quotes or a line of heredoc text counted as a redirect or a command; dscl . -read counted as an account change; and after three denials, every later call in a session asked.
  • It also found misses, now fixed: a quoted redirect target was not checked, and a cd, git -C or variable earlier in the command was ignored, so a write after cd ~/.claude/... was judged as if it were in the project.

Why not Claude Code's permission rules

Claude Code's permission rules in settings.json allow, ask or deny tool patterns, fixed per user or project. The gate adds what they lack:

  • Targets per task. The mandate lists the hosts, remotes, paths and recipients for one task, and a person changes it when the task changes.
  • Checks inside a command: which remote a git push reaches, which host a curl calls, which file a redirect writes.
  • Memory across calls: a retry of a blocked action, a run of denials.
  • An optional model judge, which can run on a local model.
  • Its own audit trail, the ledger.

The gate never answers allow, so the permission rules still apply.

Deploy as a Claude Code hook

Add this to a project's .claude/settings.json, or to ~/.claude/settings.json for every project. Use the absolute path of the installed command.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "/abs/path/to/agent_gate/.venv/bin/agent-gate hook",
            "timeout": 30,
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}
  • onFailure: "block" makes a hook timeout block the call. Without it a timed-out PreToolUse hook lets the call through.
  • The hook's timeout must exceed the model gate's timeout_seconds, or Claude Code cancels the hook before the gate can fall back to asking. The values above suit a fast model. A model as slow as Qwen3.8-27B needs both raised.
  • The gate itself always exits 0 and writes its decision as JSON. Any other non-zero exit would let the call through, which is why errors become a deny inside the gate rather than a crash.
  • When several PreToolUse hooks answer, Claude Code applies deny over defer over ask over allow, so another hook's allow cannot override this gate's deny.

Limits

  • The Bash checks are heuristics. They match URLs, user@host, git network verbs, outward verbs, identity commands, redirections and the arguments of a few file commands. A determined agent can write a command they miss, for example by building a URL from pieces. Obfuscation that the gate does recognize (a download piped to a shell, base64 -d, eval, inline Python network code) asks a person.
  • The model gate is weaker than the agent it guards. It is a second check, not a guarantee. That is why it can only tighten verdicts and why the deterministic rules come first.
  • Not verified: whether a hook deny holds under bypassPermissions mode. Claude Code's docs say deny and ask rules are still evaluated whatever a hook returns, but say nothing specific about that mode.
  • Verified (2026-12-01): a subagent's tool calls run through the same PreToolUse hook, in the parent's session, so they share its ledger and history rules. The payload names the subagent (agent_id, agent_type). In a live probe the gate denied a subagent's curl to a host outside the mandate, and Claude Code blocked the call.
  • The prompts of SendMessage and Workflow calls are not read. A subagent started through them still has its own calls judged.
  • Verified live (2026-12-01): the anthropic backend on the Claude API (claude-haiku-5-5) matched all 17 scenarios. The openai backend has run live against oMLX and Ollama.
  • Reads are never gated. An agent may read a private key; the gate only sees what it does with it next.
  • Relative paths in Bash follow a cd earlier in the same command, and a git remote follows git -C. Neither follows a cd made in an earlier call, or a directory held in a shell variable; a remote the gate cannot find asks a person.
  • A variable set to a plain path earlier in the same command is followed. A path built from another variable or a command substitution is not, and a write through it asks a person.
  • A heredoc is read as text, except when it feeds a shell. A script run from a file is not read; only the command that runs it is.
  • Reading the hook settings and piping them to python or perl in the same command is denied, since the gate cannot tell a read from a write there.
  • The ledger keeps the first 2,000 characters of each call's input. Secrets of a recognizable shape (API keys and tokens with a known prefix, Authorization headers, bearer tokens, private keys, values given to a field or flag named like a key, token, secret or password) are redacted; a secret of no recognizable shape is stored as written. A session's ledger is deleted 30 days after its last entry.

Roadmap

  1. Monitor. Read the ledger after the fact, flag sessions with denials or asks, and compare the intent lines LAWS.md asks for with what ran.
  2. Measured false positives. First replay done 2026-12-01 (see Replay real sessions). Next: other people's sessions and per-task mandates.
  3. A model-gate eval. A labeled set of harmful and ordinary actions, to choose the model and effort by measurement rather than by default.
  4. Other harnesses. An adapter for the Claude Agent SDK's hooks.

Layout

Path What it holds
LAWS.md The Laws of Agents, written as agent instructions
mandate.example.toml An annotated mandate
src/agent_gate/actions.py Hook payload to an action, description removed
src/agent_gate/mandate.py Loading and querying the mandate
src/agent_gate/rules.py Layer 1 and the history rules
src/agent_gate/model_gate.py Layer 2, with the anthropic and openai backends
src/agent_gate/ledger.py The per-session ledger
src/agent_gate/hook.py The hook protocol and evaluate
tests/ Rules, model gate and end-to-end hook tests, including the incident replay
scenarios/scenarios.toml The 17 test scenarios and their expected verdicts
scenarios/run.py Runs the scenarios through the gate and prints the results
scenarios/replay.py Replays real Claude Code sessions through the gate and counts what it flags

Citation

If you use agent-gate in your research or project, please cite it:

Suchanek, E. G. (2026). agent-gate: A Claude Code Hook That Enforces the Laws of Agents (Version 0.1.0) [Software]. Flux-Frontiers. https://github.com/Flux-Frontiers/agent_gate

@software{suchanek_agentgate,
  author    = {Suchanek, Eric G.},
  title     = {{agent-gate}: A Claude Code Hook That Enforces the Laws of Agents},
  version   = {0.1.0},
  year      = {2026},
  publisher = {Flux-Frontiers},
  url       = {https://github.com/Flux-Frontiers/agent_gate},
}

The citation metadata is also in CITATION.cff.

Metadata

Release files for agent-gate-hook 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for agent-gate-hook 0.1.0
File Size Uploaded Provenance Actions
agent_gate_hook-0.1.0.tar.gz 34.9 kB With provenance Details for agent_gate_hook-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agent-gate-hook 0.1.0
File Interpreter ABI Platform Actions
agent_gate_hook-0.1.0-py3-none-any.whl Python 3 none any Details for agent_gate_hook-0.1.0-py3-none-any.whl

Total release size: 66.2 kB

Release files / agent_gate_hook-0.1.0.tar.gz

Download URL agent_gate_hook-0.1.0.tar.gz
Size 34.9 kB
Tags Source
SHA-256 checksum
How to use checksums
777b5e5e2f0dfe252209a6de0ca916449c3eac0f46ca8709af2390d3f5772bcf
BLAKE2b-256 checksum
How to use checksums
c84ee09a92df61230b6d60495aa8f1c35a8f318eb85ed67117378f59b12eeeea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / agent_gate_hook-0.1.0-py3-none-any.whl

Download URL agent_gate_hook-0.1.0-py3-none-any.whl
Size 31.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c0f999f850ab37df2bb89ffa90339b769f49b9f6b7a3469f3cf1902a47ab5069
BLAKE2b-256 checksum
How to use checksums
fc2da0010bfa88a3f7fbc2c2f197e9f1fe13af26363a9ddbc75fe8172065ac91
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for agent-gate-hook 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for agent_gate_hook-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page