Check tool calls (Husky)¶
At the end of this guide your agent asks Husky before it runs a tool call and gets back
allow, ask or block. You will read a full verdict, connect the calls of one session (a
secret read followed by an upload), add your own policies and receivers the user already
approved, and turn shipped policies off. The examples use Ark Core in Python and Rust.
The running example: a coding assistant calls tools from MCP servers: reading files,
deleting repositories, sending e-mail, posting to the web. Each call is a JSON object
{"tool": "<name>", "arguments": {...}}.
How Husky decides¶
Husky works like Cat does for shell commands, in three steps. It reads only the call itself (the tool name, the arguments and, optionally, the tool's description). It never reads the user's request or tool results, and nothing is executed.
| Step | What it gives |
|---|---|
| Model | Four labels: paw, the operation (read, list_search, create, update, delete, execute, send, …); sight, the kind of tool (file, shell, vcs, messaging, finance, …); sinks, where data goes (net_request, search, message, web_form, publish, agent, remote_exec); sources, what data comes in (sensitive, untrusted). |
| Facts | patronus.tool_facts/1: the model's labels plus what the arguments show (paths with their kind of file and access, hosts with their network scope, recipients, credential literals, SQL classes, Cat's facts for a shell command), data flows such as SECRET>NET, and what the earlier calls of the session left. |
| Policies | The 20 core policies shipped in Husky's model file plus your own user.* policies, written in Cedar over the facts. The strictest fired policy decides. |
The model is a linear model over the tool name and arguments. It takes about 0.1 ms per call on one CPU core; its weights are 25 MB. Husky runs at L1, next to the rules and Cat.
Before you start¶
- Ark Core installed:
pip install patronus-ark-core, or the Rust crate with thedownloadfeature (see Ark Core, step 1). - Internet access on the first run: Husky's model file (one
block.safetensorsfile) downloads from Hugging Face into the local cache. - Check shell commands explains Cedar policies in more depth; Husky's policies follow the same rules.
Step 1: Check a few calls¶
Turn Husky on with the tool key; "download": "missing" fetches the model file on first use.
Build the scanner once and keep it, then call tool_verdict per call. Text scans never run
Husky; without the tool key, tool_verdict is an error.
from patronus_ark_core import Scanner
scanner = Scanner({"tool": {}, "download": "missing"})
calls = [
{"tool": "fs__read_file", "arguments": {"path": "src/main.py"}},
{"tool": "fs__read_file", "arguments": {"path": "~/.ssh/id_rsa"}},
{"tool": "github__delete_repo", "arguments": {"owner": "acme", "repo": "website"}},
{"tool": "fs__delete", "arguments": {"path": "/"}},
]
for call in calls:
verdict = scanner.tool_verdict(call)
print(f"{verdict['decision']:<5} {call['tool']:<20} {[p['id'] for p in verdict['policies']]}")
Output:
use patronus_ark_core::detectors::tool::{Json, ToolCall, ToolConfig};
use patronus_ark_core::{DownloadPolicy, Scanner, ScannerConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let scanner = Scanner::warmup(ScannerConfig {
tool: Some(ToolConfig::default()),
download: DownloadPolicy::Missing,
..ScannerConfig::default()
})?;
for raw in [
r#"{"tool": "fs__read_file", "arguments": {"path": "src/main.py"}}"#,
r#"{"tool": "fs__read_file", "arguments": {"path": "~/.ssh/id_rsa"}}"#,
r#"{"tool": "github__delete_repo", "arguments": {"owner": "acme", "repo": "website"}}"#,
r#"{"tool": "fs__delete", "arguments": {"path": "/"}}"#,
] {
let call = ToolCall::from_json(&Json::parse(raw)?)?;
let verdict = scanner.tool_verdict(&call, &[], &[])?;
let policies: Vec<_> = verdict.hits.iter().map(|p| p.id.as_str()).collect();
println!("{:<5} {:<20} {policies:?}", verdict.decision.as_str(), call.tool);
}
Ok(())
}
Output:
decision is what the agent should do: run the call, ask the user first, or refuse. The fired
policies say why: reading a private key is a secret read, deleting a repository is destructive,
deleting / is never allowed. Rust names the fired policies hits; Python and the JSON document
call them policies. A call can also carry "harness" (the agent that makes it) and
"description" (the tool's description); arguments may be an object or a string.
Step 2: Read the verdict¶
use patronus_ark_core::detectors::tool::{Json, ToolCall, ToolConfig};
use patronus_ark_core::{DownloadPolicy, Scanner, ScannerConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let scanner = Scanner::warmup(ScannerConfig {
tool: Some(ToolConfig::default()),
download: DownloadPolicy::Missing,
..ScannerConfig::default()
})?;
let call = ToolCall::from_json(&Json::parse(
r#"{"tool": "github__delete_repo", "arguments": {"owner": "acme", "repo": "website"}}"#,
)?)?;
let verdict = scanner.tool_verdict(&call, &[], &[])?;
println!("{}", serde_json::to_string_pretty(&verdict.to_json())?);
Ok(())
}
Output (Python; Rust prints the same document, shortened here):
{
"decision": "ask",
"policies": [
{
"id": "core.destructive_infra",
"tier": "core",
"decision": "ask",
"title": "Deletes in version control, cloud infrastructure, databases or secret stores"
}
],
"facts": {
"atoms": [
"TOOL_LOOSEN",
"VERB_DELETE"
],
"flows": [],
…
"model": {
"paw": "delete",
"sight": "vcs",
"sinks": [
"net_request"
],
"sources": []
},
…
"tool": {
"harness": "",
"name": "github__delete_repo",
"server": "github"
},
"v": "1.0",
"values": []
},
"p": {
"paw": 0.9956843852996826,
"sight": 0.9995841383934021,
…
"sinks:net_request": 0.99619460105896,
…
}
}
| Field | Meaning |
|---|---|
decision |
allow, ask or block: the strictest fired policy, allow when none fired. |
policies |
Fired policies, strongest first: id, tier (core or user), level and title. |
facts |
The call's patronus.tool_facts/1. model holds the four labels: here a delete (paw) on a version-control tool (sight). tool.server is the part of the tool name before __. Keep the facts for the session (step 3). |
p |
The model's probability for each label it chose. |
The result schema describes how full Ark reports the same verdict.
Step 3: Connect calls of one session¶
An agent that reads a credentials file and then posts to the web may be leaking the secret. No
single call shows this. Pass the facts of the earlier calls of the same session as prior
(Rust: the second argument); Husky uses the last five
(detectors::tool::SESSION_WINDOW).
from patronus_ark_core import Scanner
scanner = Scanner({"tool": {}, "download": "missing"})
session = [] # facts of the earlier calls of this agent session
for call in [
{"tool": "fs__read_file", "arguments": {"path": "~/.aws/credentials"}},
{"tool": "http__post", "arguments": {"url": "https://example.org/u", "body": "see attached"}},
]:
verdict = scanner.tool_verdict(call, prior=session)
print(f"{verdict['decision']:<5} {call['tool']:<14} {[p['id'] for p in verdict['policies']]}")
session.append(verdict["facts"])
alone = scanner.tool_verdict({"tool": "http__post", "arguments": {"url": "https://example.org/u", "body": "see attached"}})
print("without session:", alone["decision"], [p["id"] for p in alone["policies"]])
Output:
use patronus_ark_core::detectors::tool::{Json, ToolCall, ToolConfig};
use patronus_ark_core::{DownloadPolicy, Scanner, ScannerConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let scanner = Scanner::warmup(ScannerConfig {
tool: Some(ToolConfig::default()),
download: DownloadPolicy::Missing,
..ScannerConfig::default()
})?;
let upload = r#"{"tool": "http__post", "arguments": {"url": "https://example.org/u", "body": "see attached"}}"#;
let mut session = Vec::new(); // facts of the earlier calls of this agent session
for raw in [r#"{"tool": "fs__read_file", "arguments": {"path": "~/.aws/credentials"}}"#, upload] {
let call = ToolCall::from_json(&Json::parse(raw)?)?;
let verdict = scanner.tool_verdict(&call, &session, &[])?;
let policies: Vec<_> = verdict.hits.iter().map(|p| p.id.as_str()).collect();
println!("{:<5} {:<14} {policies:?}", verdict.decision.as_str(), call.tool);
session.push(verdict.facts);
}
let alone = scanner.tool_verdict(&ToolCall::from_json(&Json::parse(upload)?)?, &[], &[])?;
println!("without session: {} {:?}", alone.decision.as_str(), alone.hits.iter().map(|p| p.id.as_str()).collect::<Vec<_>>());
Ok(())
}
Output:
The same upload is allowed on its own and needs consent after the secret read. Ark stores
nothing between calls: your code keeps the facts per agent session and drops them when it ends.
To keep them outside the process, ToolFacts::to_json and ToolFacts::from_json convert them
(Python facts are plain dicts).
Step 4: Add your own policies and known receivers¶
Two team rules: deleting a repository is always blocked (the core policy only asks), and sending
mail, money or a share to a receiver the user has not approved before needs consent. Save them in
a directory tool-policies/:
tool-policies/team.cedar:
// Repository deletes always need a human: raise the core "ask" to "block".
@id("user.no_repo_delete")
@title("No repository deletes")
@decision("block")
forbid (principal, action == Action::"call", resource)
when { context.sight == "vcs" && context.paw == "delete" };
tool-policies/new_recipient.cedar (a copy of the opt-in example
ark-core/examples/tool_policies/new_recipient.cedar):
// Example user policy (opt-in): asks before money, a message, a contact or a share goes to a
// receiver outside known_targets (receivers the host approved before or lists it).
@id("user.new_recipient")
@decision("ask")
@title("Sends money, a message, a contact or a share to a receiver not approved before")
forbid (principal, action == Action::"call", resource)
when { !context.shell && !context.targets.isEmpty() && !context.known_targets.containsAll(context.targets) && (context.atoms.contains("TOOL_MONEY") || ["finance", "crypto"].contains(context.sight) || ["send", "create", "update"].contains(context.paw)) };
List the directory in policy_dirs. The receivers the user approved go into known_targets
per call:
from patronus_ark_core import Scanner
scanner = Scanner({"tool": {"policy_dirs": ["tool-policies"]}, "download": "missing"})
delete = {"tool": "github__delete_repo", "arguments": {"owner": "acme", "repo": "website"}}
verdict = scanner.tool_verdict(delete)
print(f"{verdict['decision']:<5} delete repo {[p['id'] for p in verdict['policies']]}")
mail = {"tool": "gmail__send_email", "arguments": {"to": "billing@partner.example", "subject": "Invoice", "body": "Attached."}}
verdict = scanner.tool_verdict(mail)
print(f"{verdict['decision']:<5} mail, new receiver {[p['id'] for p in verdict['policies']]}")
verdict = scanner.tool_verdict(mail, known_targets=["billing@partner.example"])
print(f"{verdict['decision']:<5} mail, known receiver {[p['id'] for p in verdict['policies']]}")
Output:
use patronus_ark_core::detectors::tool::{Json, ToolCall, ToolConfig};
use patronus_ark_core::{DownloadPolicy, Scanner, ScannerConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut tool = ToolConfig::default();
tool.policy_dirs.push("tool-policies".into()); // every *.cedar file in it
let scanner = Scanner::warmup(ScannerConfig {
tool: Some(tool),
download: DownloadPolicy::Missing,
..ScannerConfig::default()
})?;
let delete = ToolCall::from_json(&Json::parse(
r#"{"tool": "github__delete_repo", "arguments": {"owner": "acme", "repo": "website"}}"#,
)?)?;
let verdict = scanner.tool_verdict(&delete, &[], &[])?;
let policies: Vec<_> = verdict.hits.iter().map(|p| p.id.as_str()).collect();
println!("{:<5} delete repo {policies:?}", verdict.decision.as_str());
let mail = ToolCall::from_json(&Json::parse(
r#"{"tool": "gmail__send_email", "arguments": {"to": "billing@partner.example", "subject": "Invoice", "body": "Attached."}}"#,
)?)?;
let verdict = scanner.tool_verdict(&mail, &[], &[])?;
let policies: Vec<_> = verdict.hits.iter().map(|p| p.id.as_str()).collect();
println!("{:<5} mail, new receiver {policies:?}", verdict.decision.as_str());
let known = ["billing@partner.example".to_string()];
let verdict = scanner.tool_verdict(&mail, &[], &known)?;
let policies: Vec<_> = verdict.hits.iter().map(|p| p.id.as_str()).collect();
println!("{:<5} mail, known receiver {policies:?}", verdict.decision.as_str());
Ok(())
}
Output:
Your policy raises the repository delete to block; the core policy still fires and is listed
too. The mail asks while the receiver is new and is allowed once it is in known_targets. The
receivers a call addresses are in its facts as targets. Inline policies (Cedar source strings)
go into policies next to policy_dirs; they are applied after the files.
Rules for a user policy¶
User policies use the same format as Cat's:
forbidonly;@id("user.<name>"),@decision("block")or@decision("ask"), and an optional@title;action == Action::"call", principal and resource unconstrained;- each policy is validated against the schema
data/tool.cedarschema; an invalid one stops the scanner from being built, with the reason (Python:RuntimeError, Rust:ScanError::Tool).
What a policy can read (context.*):
| Group | Fields |
|---|---|
| The call and the model | tool, server, paw, sight, sinks, sources |
| Files | objects ("<ACCESS>@<CLASS>"), classes |
| Network and receivers | hosts, net_scopes, recipient_kinds, recipient_domains, targets, known_targets |
| Content | atoms, flows ("<DATA>><SINK>", "<DATA>><SINK>><VIA>"), shell, external |
| Session | session_sources, session_tool_sources, session_objects, linked |
Step 5: Turn shipped policies off¶
Every Husky policy is also an L1 rule with the id tool.<policy id> (tool.core.secret_read,
tool.user.no_repo_delete). The rules key turns it off, like any other rule.
from patronus_ark_core import Scanner
call = {"tool": "fs__read_file", "arguments": {"path": "~/.ssh/id_rsa"}}
default = Scanner({"tool": {}, "download": "missing"})
print("default:", default.tool_verdict(call)["decision"])
relaxed = Scanner({"tool": {}, "rules": {"tool.core.secret_read": False}, "download": "missing"})
print("relaxed:", relaxed.tool_verdict(call)["decision"])
Output:
use patronus_ark_core::detectors::tool::{Json, ToolCall, ToolConfig};
use patronus_ark_core::{DownloadPolicy, Scanner, ScannerConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let call = ToolCall::from_json(&Json::parse(
r#"{"tool": "fs__read_file", "arguments": {"path": "~/.ssh/id_rsa"}}"#,
)?)?;
let config = ScannerConfig {
tool: Some(ToolConfig::default()),
download: DownloadPolicy::Missing,
..ScannerConfig::default()
};
let default = Scanner::warmup(config.clone())?;
println!("default: {}", default.tool_verdict(&call, &[], &[])?.decision.as_str());
let mut relaxed_config = config;
relaxed_config.gates.rules.insert("tool.core.secret_read".into(), false);
let relaxed = Scanner::warmup(relaxed_config)?;
println!("relaxed: {}", relaxed.tool_verdict(&call, &[], &[])?.decision.as_str());
Ok(())
}
Output:
With core.secret_read off, nothing else fires for this call, so it is allowed. In Rust,
Scanner::reload_tool replaces the user policies at runtime without reloading the model file,
like Cat's reload_shell; a refused config changes nothing.
The core policies¶
| Level | Policies |
|---|---|
| block | secret material or a credential literal sent out; code fetched from the network and run; link-local (cloud metadata) address; root or home deleted; sending reuses the path of a secret read earlier |
| ask | persistence or system location written; secret read; destructive SQL; credential literal in the arguments; deletes in version control, cloud, databases or secret stores; after untrusted input: remote execution, publishing or messaging; after sensitive data: sending it to an external target; after a secret read: any egress; after untrusted input or reused data: money movement, loosening a security control, controlling a physical device, deleting accounts, posting publicly |
The action policies (money, security, devices, accounts, posts) ask only after untrusted input in the session, or when the call reuses data of an untrusted or sensitive call. A call alone cannot show whether the user asked for the action.
Options¶
tool keys (Python dict, Rust ToolConfig):
| Key | Default | Meaning |
|---|---|---|
block_path |
<cache_root>/tool_call/husky_tool_call_commander/block.safetensors |
Husky's model file. |
block_sha256 |
the pin compiled into the library (warmup::TOOL_BLOCK_SHA256) |
SHA-256 the file must have; a changed file is refused. |
policy_dirs |
none | Directories whose *.cedar files are your user policies. |
policies |
none | Inline Cedar user policies, applied after the files. |
max_input_bytes of the scanner config also limits the size of a call's JSON text.
download: "missing" fetches block.safetensors and the release's config.json of
patronus-studio/husky-tool-call-commander
at warmup::TOOL_REVISION; download_categories: ["tool_call"] limits downloads to Husky. The
config.json must name a tool-call block and list the pinned SHA-256; every load checks it.
Without a scanner (Rust)¶
detectors::tool::ToolAssessor is Husky alone, without a Scanner. This program takes the
model file and a policy directory as arguments:
use std::path::Path;
use patronus_ark_core::detectors::tool::{Json, ToolAssessor, ToolCall, ToolFacts};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Usage: assess <block.safetensors> <policy dir>
let args: Vec<String> = std::env::args().collect();
let assessor = ToolAssessor::load(
Path::new(&args[1]), // Husky's model file
None, // or Some("<sha256 of the file>") to pin it
&[Path::new(&args[2])], // your *.cedar files
)?;
let call = ToolCall::from_json(&Json::parse(
r#"{"tool": "github__delete_repo", "arguments": {"owner": "acme", "repo": "website"}}"#,
)?)?;
let session: Vec<ToolFacts> = Vec::new(); // facts of earlier calls, kept by you
let verdict = assessor.assess(&call, &session, &[], |_rule_id| true)?; // every policy on
let policies: Vec<_> = verdict.hits.iter().map(|p| p.id.as_str()).collect();
println!("{} {policies:?}", verdict.decision.as_str());
Ok(())
}
Output, run with the cached model file (macOS cache path) and the tool-policies directory from
step 4:
The last argument of assess decides per rule id whether a policy is on. assess_with_labels
takes paw, sight, sinks and sources from you instead of the model, which helps in tests
and in hosts that already know the tool type.
From the command line¶
The repository's tool_facts example reads one call per line ({"session"?, "tool",
"arguments", "harness"?, "description"?, "known_targets"?}; calls with the same session see
each other) and prints one verdict per line ({"decision", "policies", "facts", "p"}):
cargo run --release -p patronus-ark-core --example tool_facts -- \
/srv/models/husky-tool-call-commander/block.safetensors ark-core/examples/tool_policies < calls.jsonl
The model file, with or without Ark¶
A release is one patronus.block/1 file: block.safetensors holds the weights, and its
metadata holds the vocabularies, label heads, thresholds, core policies and Cedar schema. Next to
it in the Hugging Face repository, block.py is the reference implementation in one file (it
needs numpy, safetensors and cedarpy). Ark runs a Rust port of the same code on the same
file; the repository's tests/blocks.rs checks that both give the same decisions, policies and
facts, and tests/tool_facts_goldens.rs and tests/tool_model_parity.rs check facts and model
scores. Without Ark:
import block # block.py from the model's Hugging Face repository
b = block.from_pretrained("<repo>") # downloads block.safetensors with huggingface_hub
verdict = b.assess({"tool": "gmail__send_email", "arguments": {"to": "billing@partner.example", "body": "hi"}})
Ark refuses a model file whose Cedar schema or shell vocabulary differs from the ones it was
built with, because it would then read different facts than the file's block.py. The core
policies come only from the file; Ark compiles in no copy of them.
Full Ark: the tool_call category¶
In full Ark, Husky is the category tool_call. The gateway prepares and loads the same model
file in warmup and takes the same tool key. It scans a call given as JSON text
({"tool", "arguments", "harness"?, "description"?}) without session context and reports
class_name tool_risk (ask or block) or safe, with details.decision and
details.verdict (the verdict above). SecurityGateway::tool_config and reload_tool mirror
Cat's shell_config and reload_shell. The HTTP API takes the tool key under pipeline and
the tool_call category in requests. Use the Core scanner when you need sessions or known
receivers.
This program scans three of the calls from step 1 with the gateway. It reads the policies from
the tool-policies/ directory of step 4, so run it in the same folder:
import json
from patronus_ark import SecurityGateway
gateway = SecurityGateway({
"categories": ["tool_call"],
"max_level": "l1",
"download": "missing",
"tool": {"policy_dirs": ["tool-policies"]},
})
gateway.warmup()
calls = [
{"tool": "fs__read_file", "arguments": {"path": "src/main.py"}},
{"tool": "github__delete_repo", "arguments": {"owner": "acme", "repo": "website"}},
{"tool": "fs__delete", "arguments": {"path": "/"}},
]
for call in calls:
result = gateway.scan_categories(["tool_call"], json.dumps(call))["native"][0]
verdict = result["layers"][0]["details"]["verdict"]
print(f"{result['class_name']:<9} {verdict['decision']:<5} {call['tool']:<20} {[p['id'] for p in verdict['policies']]}")
Output:
safe allow fs__read_file []
tool_risk block github__delete_repo ['user.no_repo_delete', 'core.destructive_infra']
tool_risk block fs__delete ['core.root_delete']
Each call is one tool_call result. Reading a source file is safe (allow). Deleting a
repository is now block: your policy user.no_repo_delete from step 4 raises the core policy's
ask. Deleting / is blocked by the core policy core.root_delete. The result's model is
husky-tool-call-commander and its confidence is 1.0, because a policy decision is not a
probability. The constructor raises ValueError on an unreadable policy directory.
What's next¶
- Check shell commands (Cat): the same kind of verdict for shell commands.
- Ark Core tutorial: text scans, built-in L1 models and Wolf in the same scanner.
- Result schema: tool call results.