stalwart_agents.guardrails

A deterministic guardrail for the tool calls any LLM agent makes.

from stalwart_agents.guardrails import Guardrail, checks

rail = Guardrail(tools=request["tools"], rules="rules.yaml",
                 checks=[checks.AllowList(), checks.Schema(), checks.Destinations(), checks.Order(),
                         checks.Rules(), checks.Taint(), checks.Grounded(), checks.S1Veto(mode="refuse")],
                 on_fail={"refuse": "exception", "confirm": "ask"})
verdict = rail.check_call({"tool": "refund_card", "arguments": {...}}, context={"turns": [...], "results": {...}})
verdict.decision, verdict.rule, verdict.reason, verdict.decision_id

Each call is answered allow, confirm (ask the person) or refuse, naming the check that decided. The checks are listed, with what each catches and cannot catch, in registry; the answer comes from the licensed tool check and the admission chain, with the checks of what the turn said (grounding, the S1 and S2 vetoes, the confirm read) only ever making it stricter. Nothing in a decision is guessed by a language model, and importing this package loads no model.

On top of Guardrails AI: stalwart_agents.guardrails.gai. On NeMo Guardrails: stalwart_agents.guardrails.nemo.

class CallRefused(builtins.Exception):

The guardrail refused a call (on-fail exception): nothing may run. verdict says which check and why.

Example:

refused = CallRefused(Verdict("refuse", "t", "allowed_tools", "t is not one of your tools.", "chk_1")) str(refused) 't refused by allowed_tools: t is not one of your tools.'

CallRefused(verdict: Verdict)
verdict
class ConfirmationNeeded(builtins.Exception):

A call waits for a person (on-fail exception for a confirmation): show payload, and on their yes pass Guardrail.approve(payload) as the context's confirmation.

Example:

asked = ConfirmationNeeded(Verdict("confirm", "t", "any_other_write", "Run t?", "chk_1", ... confirmation={"token": "slg1.x.-"})) asked.payload["token"] 'slg1.x.-'

ConfirmationNeeded(verdict: Verdict)
verdict
payload
class Guardrail:

Checks each tool call an LLM agent proposes before it runs.

Args: catalogue: the tools: a path to a JSON file, a list (OpenAI, Anthropic, MCP or LangChain tools) or a mapping with tools. tools is the same, for a tools= list as it was handed to the model. rules: a rule sheet (compiled by the service at set-up), a compiled folder, or rulebook IR. checks: the checks to run (stalwart_agents.guardrails.checks); all, at their defaults, where None. on_fail: what a failure does: {"refuse": "exception" | "refrain" | "noop", "confirm": "ask" | "exception" | "refrain"}. A check's own on_fail wins for that check. tool_kinds: the tool kinds file (a path or a mapping). infer_tool_kinds: whether the kinds of tools nobody marked are inferred (else each is a write). agent: the agent the calls are made for. settings: the tool check's settings (taint_policy, confirmation_ttl_seconds). client: the Client whose licensed runtime answers; one is made from QLS_API_KEY where needed. runtime: reaches the runtime directly, in place of @p client's (a test's stand-in). record: keep each decision for explain_decision (names and digests only); or a decisions.Record. admission_chain: the admission chain; the default chain's switched-on checks where None.

Example:

rail = Guardrail(tools=[{"name": "get_order", "input_schema": {"type": "object"}}], ... runtime=lambda op, body: {"answer": "allow", "decided_by": "allow"}, record=False) rail.check_call({"tool": "get_order", "arguments": {"order_id": "A1"}}).proceed True

Guardrail( catalogue: Any = None, *, tools: Any = None, rules: Any = None, checks: Sequence[stalwart_agents.guardrails.checks.Setting] | None = None, on_fail: Mapping[str, str] | None = None, tool_kinds: str | pathlib.Path | Mapping[str, Any] | None = None, infer_tool_kinds: bool = True, agent: str = 'agent', settings: Mapping[str, Any] | None = None, client: Any = None, runtime: Callable[[str, Mapping[str, Any]], Any] | None = None, record: bool | stalwart_agents.guardrails.decisions.Record = True, admission_chain: list[Any] | None = None, vocabulary: str | None = None, language: str | None = None, sentences: str = 'en', assume_ran: bool = True, turns_in: str = 'en')
language
assume_ran
turns_in
agent
client
kinds_file
infer_tool_kinds
base
settings
on_fail
check_settings
catalogue
chain
record
fixed
@classmethod
def from_mcp( cls, server: str, *, base: str | pathlib.Path = '.', **options: Any) -> Guardrail:

A guardrail over an MCP server's tools: @p server is its address, or a saved tools/list reply.

Args: server: the server's address, or a saved tools/list reply. base: the folder a saved reply is read from. **options: the guardrail's own.

Returns: The guardrail.

Raises: ValueError: a server that lists no tools.

def search_wordings( self, language: str = 'en', *, checks: Sequence[str] | None = None, seconds: float = 120.0, slips: int = 1, joins: bool = True) -> dict[str, Any]:

The wording search over this guardrail's catalogue (search.Search): every wording within each reader check's cone, read by the real reader, with the bounds, the time read and whether each search finished on the report.

@p checks: any of s1_veto, s2_veto, confirm_read; all where None. @p seconds: each check's time budget (0 is unbounded).

Args: language: the language the turns are in (en or pt-BR). checks: the checks searched. seconds: each check's time budget. slips: whether each sending verb's slip is read. joins: whether instructions joined to a reading one are read.

Returns: The report, a check at a time.

def kind_of(self, tool: str) -> str:

@p tool's kind (read, write, sends_out), or unknown for a tool this guardrail does not hold.

Returns: The kind.

def session( self, session: str = 'default') -> stalwart_agents.client.History:

The history of @p session's calls, as the guardrail carries it.

Returns: The session's history.

def check_call( self, call: Any, context: Mapping[str, Any] | None = None) -> Verdict:

The answer for one proposed call, with the on-fail action applied.

@p context: turns (the person's turns, latest last), language (the turns' language, en or pt-BR, where it is not the guardrail's turns_in), results (what tools returned, by call or tool), session (keeps one conversation's history apart), confirmation (a token from approve), labels, origins, plan, plan_token, usage.

Raises: CallRefused: a refusal whose on-fail action is exception. ConfirmationNeeded: a confirmation whose on-fail action is exception. SelectorUnavailableError: no licensed runtime answers here: the call is blocked, never allowed.

Args: call: the call, in our shape or a provider's. context: what the checks read, as above.

Returns: The verdict, its on-fail action applied.

def decide( self, call: Any, context: Mapping[str, Any] | None = None) -> Verdict:

The answer for one proposed call, with no on-fail action applied.

Args: call: the call, in our shape or a provider's. context: what the checks read (see check_call).

Returns: The verdict.

def approve(self, payload: Mapping[str, Any]) -> str:

The token a person's yes gives @p payload: pass it as the context's confirmation with the same call. A changed call, or one checked after the session moved on, is asked about again.

Returns: The token.

def act( self, verdict: Verdict) -> Verdict:

@p verdict with its on-fail action applied.

Returns: The verdict, with action and proceed set.

Raises: CallRefused: a refusal whose on-fail action is exception. ConfirmationNeeded: a confirmation whose on-fail action is exception.

def ran( self, verdict: Verdict, outcome: str = 'ran', session: str = 'default') -> None:

Reports what became of an allowed call (ran, failed, outcome_unknown), so the order rules count it.

Args: verdict: the allowed call's verdict. outcome: what became of it. session: its session.

@dataclass
class Verdict:

One call's answer.

decision is allow, confirm or refuse; rule the registry name of the check that decided (empty for an allow); reason its sentence; decided_by the tool check's or admission chain's own name for it; findings what each check of the turn found; confirmation the payload a person approves; action the on-fail action taken (exception, refrain, noop, ask, or empty for an allow); proceed whether the caller may run the call.

Example:

Verdict("allow", "get_order", "", "", "chk_1", proceed=True).to_dict()["decision"] 'allow'

Verdict( decision: str, tool: str, rule: str, reason: str, decision_id: str, decided_by: str = '', detail: dict[str, Any] = <factory>, findings: list[dict[str, Any]] = <factory>, confirmation: dict[str, Any] | None = None, action: str = '', proceed: bool = False, kind: dict[str, str] = <factory>, step: int = -1)
decision: str
tool: str
rule: str
reason: str
decision_id: str
decided_by: str = ''
detail: dict[str, Any]
findings: list[dict[str, Any]]
confirmation: dict[str, Any] | None = None
action: str = ''
proceed: bool = False
kind: dict[str, str]
step: int = -1
def to_dict(self) -> dict[str, Any]:

The verdict as plain data: names and digests, no argument value.

Returns: The verdict's fields, the confirmation without the call.

def as_call(call: Any) -> dict[str, Any]:

One tool call as {"tool", "arguments", "id"?} from our shape, an OpenAI tool call (function.arguments as JSON), an Anthropic tool_use block, a LangChain ToolCall, or an object with those attributes.

Example:

as_call({"type": "function", "id": "c1", "function": {"name": "f", "arguments": "{\"a\": 1}"}}) {'tool': 'f', 'arguments': {'a': 1}, 'id': 'c1'} as_call({"type": "tool_use", "id": "t1", "name": "g", "input": {"b": 2}}) {'tool': 'g', 'arguments': {'b': 2}, 'id': 't1'} as_call({"name": "h", "args": {"c": 3}, "id": "l1"}) {'tool': 'h', 'arguments': {'c': 3}, 'id': 'l1'}

Args: call: the call, in any of the shapes above, or its JSON.

Returns: The call in our shape.

Raises: ValueError: a call that names no tool.