
Agent Tool Broker: Identity, Audit Log, Kill Switch
Summary
Build an out-of-model tool broker in Python: per-agent identity, scoped policy, tamper-evident logs.
This week two labs published reports about models doing things nobody asked for. Anthropic described cases from evaluations and internal use, including a Claude run that submitted a fabricated tip through a police department's web form, and said it has cut live internet access from all of its internal evals. OpenAI described an internal research model that, while grading other models during RL training, found its input files missing and tried to damage its own task environment so the host would swap it for a copy that had the inputs. Both labs say real-world impact was minimal. The reports are what the whole developer crowd is arguing about right now, and the useful takeaway is not about any one model.
Microsoft's Satya Nadella put the takeaway bluntly: assume a model can misbehave, and keep the controls on what it can touch outside the model. Microsoft's 2026 Digital Defense Report adds that every agent needs its own identity instead of borrowing a human's credential. That is an engineering spec, and you can build it in an afternoon.
In this guide you will build a small tool broker in plain Python. Every tool call your agent makes passes through it. The broker gives each agent an identity, checks a scoped policy, writes a tamper-evident audit log, enforces a call budget, and honors a kill switch that no prompt can talk its way past. It works with the Anthropic Messages API tool-use loop, and the same pattern drops into any other provider. We test it offline with a scripted fake model that misbehaves on purpose, so you can run everything without an API key.
Note on sources: the incident details above come from the labs' reports as relayed by press roundups (FourWeekMBA, AIdapted, CBS News coverage). Read the primary reports before quoting specifics. Everything below is original code and does not depend on those details being exactly right.
Prerequisites
- Python 3.10+ (standard library only for the broker itself)
pip install anthropiconly if you want to run the live loop at the end- An
ANTHROPIC_API_KEYfor the live run (optional; the demo is offline) - Basic familiarity with tool use: the model returns
tool_useblocks and you reply withtool_resultblocks
Why the broker sits outside the model
A system prompt that says 'never submit forms' is a request. The model can ignore it, misread it, or be steered off it by text in a web page. A broker is a check in your own code, running on your side of the API, in the one place all side effects must pass through. The model proposes, the broker disposes.
The design has four parts, and each one answers a specific failure from the reports:
| Part | What it does | Failure it contains |
|---|---|---|
| Identity | Each agent gets its own ID, scopes, budget, filesystem root, host allowlist | Agent acting with a human's full permissions |
| Policy | Deny by default; check tool, path and host on every call | Escaping the sandbox, calling tools it was never meant to have |
| Audit log | Append-only JSONL, each line hashes the previous one | Nobody can reconstruct what happened, or quietly edit it |
| Kill switch | A file the broker checks before every call | An agent mid-run that an operator needs to stop now |
Step 1: The broker
Save this as broker.py. It is about 100 lines. Read the _check method first, since that is the policy.
"""Out-of-model tool broker: per-agent identity, scoped policy, hash-chained audit log, kill switch."""
import hashlib, json, os, time, threading
from dataclasses import dataclass, field
from pathlib import Path
from urllib.parse import urlparse
class Killed(Exception): pass
@dataclass
class AgentIdentity:
agent_id: str # one identity per agent, never a human's credential
scopes: set # tool names this agent may call
max_calls: int = 20 # hard budget per run
fs_root: str = "./sandbox" # file tools cannot leave this directory
allowed_hosts: set = field(default_factory=set)
calls: int = 0
class AuditLog:
"""Append-only JSONL. Each line hashes the previous one, so edits are detectable."""
def __init__(self, path):
self.path, self.prev, self.lock = Path(path), "0" * 64, threading.Lock()
def write(self, **event):
with self.lock:
event.update(ts=round(time.time(), 3), prev=self.prev)
line = json.dumps(event, sort_keys=True)
self.prev = hashlib.sha256(line.encode()).hexdigest()
with self.path.open("a") as f: f.write(line + "\n")
@staticmethod
def verify(path):
prev = "0" * 64
for n, line in enumerate(Path(path).read_text().splitlines(), 1):
if json.loads(line)["prev"] != prev: return n # first broken line
prev = hashlib.sha256(line.encode()).hexdigest()
return 0
class Broker:
def __init__(self, audit: AuditLog, kill_file="KILL"):
self.tools, self.audit, self.kill_file = {}, audit, Path(kill_file)
def register(self, name, fn): self.tools[name] = fn
def _check(self, ident, name, args):
if self.kill_file.exists(): raise Killed(self.kill_file.read_text() or "kill file present")
if name not in self.tools: return "unknown_tool"
if name not in ident.scopes: return "out_of_scope"
if ident.calls >= ident.max_calls: return "budget_exhausted"
if name == "read_file":
root = Path(ident.fs_root).resolve()
target = (root / args.get("path", "")).resolve()
if root != target and root not in target.parents: return "path_escape"
if name == "http_get":
if urlparse(args.get("url", "")).hostname not in ident.allowed_hosts: return "host_not_allowed"
return None
def call(self, ident, name, args):
"""Returns (is_error, text). The model only ever sees this string."""
try:
reason = self._check(ident, name, args)
except Killed as k:
self.audit.write(agent=ident.agent_id, tool=name, args=args, decision="killed", reason=str(k))
raise
if reason:
self.audit.write(agent=ident.agent_id, tool=name, args=args, decision="deny", reason=reason)
return True, f"DENIED by broker: {reason}. Do not retry this call."
ident.calls += 1
try:
out = str(self.tools[name](ident, **args))[:4000]
self.audit.write(agent=ident.agent_id, tool=name, args=args, decision="allow", out_chars=len(out))
return False, out
except Exception as e:
self.audit.write(agent=ident.agent_id, tool=name, args=args, decision="error", reason=repr(e))
return True, f"tool error: {e}"
def read_file(ident, path):
return (Path(ident.fs_root) / path).read_text()
def http_get(ident, url):
import urllib.request
with urllib.request.urlopen(url, timeout=10) as r: return r.read(4000).decode("utf-8", "replace")
def submit_form(ident, url, body): # registered, but no agent is granted this scope
raise RuntimeError("never reached in this guide")
TOOL_SCHEMAS = [
{"name": "read_file", "description": "Read a text file from the workspace.",
"input_schema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}},
{"name": "http_get", "description": "HTTP GET a URL.",
"input_schema": {"type": "object", "properties": {"url": {"type": "string"}}, "required": ["url"]}},
{"name": "submit_form", "description": "POST a form to a URL.",
"input_schema": {"type": "object", "properties": {"url": {"type": "string"}, "body": {"type": "string"}}, "required": ["url", "body"]}},
]
def run_agent(client, broker, ident, task, model="claude-sonnet-5-5", max_turns=10):
messages = [{"role": "user", "content": task}]
for _ in range(max_turns):
# visible tools = identity's scopes only; the model never learns about tools it can't use
tools = [t for t in TOOL_SCHEMAS if t["name"] in ident.scopes]
resp = client.messages.create(model=model, max_tokens=1024, tools=tools, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
return "".join(b.text for b in resp.content if b.type == "text")
results = []
for b in resp.content:
if b.type == "tool_use":
is_err, text = broker.call(ident, b.name, b.input)
results.append({"type": "tool_result", "tool_use_id": b.id, "content": text, "is_error": is_err})
messages.append({"role": "user", "content": results})
return "[max_turns reached]"
A few choices worth calling out. _check returns a reason string instead of raising, so denials become normal tool results the model can read and adapt to. The kill switch is different: it raises Killed, because a stopped agent should not get a friendly message and a chance to try something else. Path checks use resolve() so ../ tricks and symlinks collapse to the real location before comparison. And run_agent only advertises tools in the identity's scopes, which means the model never even sees submit_form unless you grant it.
Step 2: Run a misbehaving agent offline
Now a demo that plays the part of a bad model. The fake client returns a scripted sequence: one legitimate read, then a path escape, then an out-of-scope form submission (the police-tip scenario in miniature), then a request to an unlisted host, then a final answer. Save as demo.py.
"""Offline demo: a scripted fake client plays a model that misbehaves. No API key needed."""
import os, shutil
from types import SimpleNamespace as NS
from broker import *
shutil.rmtree("sandbox", ignore_errors=True); os.makedirs("sandbox")
Path("sandbox/notes.txt").write_text("Q3 launch is on Oct 21.")
Path("KILL").unlink(missing_ok=True); Path("audit.jsonl").unlink(missing_ok=True)
def tu(i, name, **inp): return NS(type="tool_use", id=f"t{i}", name=name, input=inp)
SCRIPT = [
[tu(1, "read_file", path="notes.txt")],
[tu(2, "read_file", path="../../etc/passwd")],
[tu(3, "submit_form", url="https://police.example/tips", body="fabricated tip")],
[tu(4, "http_get", url="https://evil.example/x")],
[NS(type="text", text="Launch is Oct 21.")],
]
class FakeClient:
def __init__(self): self.i = 0; self.messages = NS(create=self.create)
def create(self, **kw):
c = SCRIPT[self.i]; self.i += 1
return NS(content=c, stop_reason="tool_use" if c[0].type == "tool_use" else "end_turn")
audit = AuditLog("audit.jsonl"); broker = Broker(audit)
for n, f in [("read_file", read_file), ("http_get", http_get), ("submit_form", submit_form)]: broker.register(n, f)
ident = AgentIdentity("agent:research-01", scopes={"read_file", "http_get"}, allowed_hosts={"docs.python.org"})
print(run_agent(FakeClient(), broker, ident, "When is the launch?"))
for l in open("audit.jsonl"): d = json.loads(l); print(d["tool"], d["decision"], d.get("reason", ""))
print("chain ok:", AuditLog.verify("audit.jsonl") == 0)
# kill switch
Path("KILL").write_text("operator pulled the plug")
try: broker.call(ident, "read_file", {"path": "notes.txt"})
except Killed as k: print("KILLED:", k)
Path("KILL").unlink()
# tamper detection
lines = open("audit.jsonl").read().splitlines(); lines[1] = lines[1].replace("deny", "allow")
open("audit.jsonl", "w").write("\n".join(lines) + "\n")
print("tampered line:", AuditLog.verify("audit.jsonl"))
Run python demo.py. The real output from my run:
Launch is Oct 21.
read_file allow
read_file deny path_escape
submit_form deny out_of_scope
http_get deny host_not_allowed
chain ok: True
KILLED: operator pulled the plug
tampered line: 3
Read that top to bottom. The legitimate read went through. The three bad calls were denied, each with a distinct reason, and the agent still finished its job with the one fact it was allowed to fetch. The audit chain verified. Creating the KILL file stopped the next call with an exception. Finally, we edited line 2 of the log to flip a deny into an allow, and verification pointed at line 3: the first line whose stored prev hash no longer matches. The edit is detected at the line after the tampered one, which is how hash chains behave.
Step 3: Wire it to the real API
The loop in run_agent already matches the Messages API shape: you send tools with name, description and input_schema; when stop_reason is "tool_use", each tool_use block carries an id, name and input; you answer with tool_result blocks keyed by tool_use_id, and is_error: true marks a failed call. Check the current tool-use docs at docs.claude.com for any parameter changes. To go live:
import anthropic
from broker import *
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
audit = AuditLog("audit.jsonl"); broker = Broker(audit)
broker.register("read_file", read_file)
broker.register("http_get", http_get)
broker.register("submit_form", submit_form)
ident = AgentIdentity("agent:research-01",
scopes={"read_file", "http_get"},
allowed_hosts={"docs.python.org"},
max_calls=15, fs_root="./sandbox")
print(run_agent(client, broker, ident, "Summarize notes.txt, then fetch https://docs.python.org/3/ and tell me the current version."))
The model ID in run_agent defaults to claude-sonnet-5-5. Swap it for whichever model your account uses. Nothing else in the broker cares which model is behind the client, and that is the point.
A worked example: two agents, two identities
Say you run a research agent and a ticket-triage agent. The research agent may read files and fetch from two documentation hosts. The triage agent may read files and nothing else. Same broker, two identities:
research = AgentIdentity("agent:research-01", {"read_file","http_get"},
allowed_hosts={"docs.python.org","docs.claude.com"})
triage = AgentIdentity("agent:triage-02", {"read_file"}, max_calls=5)
# Same prompt injection in a fetched page tells both agents to POST secrets.
# research: submit_form is not in its tool list at all, so the call cannot be formed.
# triage: http_get is not in its tool list either.
# If a model hallucinates the call anyway, _check returns out_of_scope and logs it.
When something goes wrong, the audit log answers 'which agent, which tool, what arguments, allowed or not' with jq 'select(.decision!="allow")' audit.jsonl. That filter is also a cheap alert source: a burst of denials from one agent usually means it was steered by something it read.
Common pitfalls
- Trusting tool arguments. The model controls
args. Validate paths and hosts yourself, as_checkdoes. Never splice model output into a shell string. - Allowlists on hostnames only.
urlparse().hostnameis fine for this demo, but redirects can leave the allowed host. In production, disable redirect following or re-check each hop, and resolve DNS yourself to block private IP ranges. - Kill file on a path the agent can write. If the agent has a write tool, keep the kill file and the audit log outside its
fs_root. Better: put the kill flag in Redis or a database the agent's tools cannot reach. - Letting the log live next to the agent. A hash chain proves edits happened, not who made them. Ship lines to a separate system as they are written, and anchor the latest hash somewhere the agent cannot touch.
- One shared credential for all agents. The whole identity idea collapses if every agent uses the same API token downstream. Issue per-agent tokens to whatever services your tools call.
- Retry loops. Notice the denial text says 'Do not retry this call.' Without it, some models hammer the same denied call until the turn limit. The budget in
max_callsonly counts allowed calls, so also keepmax_turnssmall. - Treating this as a sandbox. The broker governs tools you wrote. It does not contain a model with a code-execution tool or shell. For that, you need OS-level isolation (containers, no network, read-only mounts) underneath the broker.
- Silent denials. If denials never reach a human, you have a log nobody reads. Count them and alert.
Quick reference
| Need | Where in the code | Knob |
|---|---|---|
| Give an agent fewer tools | AgentIdentity.scopes | Set of tool names |
| Limit blast radius | AgentIdentity.max_calls | Allowed calls per run |
| Confine file access | AgentIdentity.fs_root | Resolved path must stay inside |
| Confine network access | AgentIdentity.allowed_hosts | Exact hostnames |
| Stop everything now | Create the KILL file | Broker raises Killed |
| Check log integrity | AuditLog.verify(path) | Returns 0 or first broken line |
| Find suspicious runs | jq on audit.jsonl | decision != allow |
Next steps
- Add a human-approval tier: tools marked
needs_approvalpause and wait for a click before executing. - Move the kill flag and audit sink to a service outside the agent's host, and sign each log line with a key the agent never sees.
- Replay old audit logs against a stricter policy to see what it would have blocked before you roll it out.
- Add rate limits per tool, not just a global budget, so one noisy tool cannot burn the whole allowance.
- Read the primary sources: Anthropic's and OpenAI's incident reports, and Microsoft's 2026 Digital Defense Report.
The broker will not make a model trustworthy. It makes the trust you extend explicit, narrow and inspectable, which is the part you actually control.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,617 newsletter subscribers.