recusal-openai-agents

The Recusal gate for the
OpenAI Agents SDK: every function tool
call an agent proposes is judged by your policy before the tool runs, and a refused call
never runs.
New to Recusal? It checks each tool call an AI agent proposes against your policy and
refuses the unsafe or unapproved ones before the tool runs. No model makes that decision.
A policy is a plain Python function: it is given the tool's name and its arguments and
returns a list of findings. An empty list lets the call run; a failing finding refuses it
and gives the reason.
Writing a policy
covers the two postures, allowlist and deny-list.
This is a separate distribution from recusal. The kernel has zero runtime dependencies
and a frozen compatibility perimeter; this package carries the SDK dependency and its own
version, so an SDK release never forces a release of the kernel.
Install it from PyPI:
pip install recusal-openai-agents
Requires Python 3.10+ (the SDK's minimum), recusal>=0.17.0 and openai-agents>=0.24.0.
It is tested on every pull request against exactly openai-agents==0.24.0 with
openai==3.49.0, and weekly against the newest releases.
The package ships inline types (py.typed) for your editor and type checker.
Use
from agents import Agent, function_tool
from recusal import Finding
from recusal_openai_agents import gated_agent
@function_tool
def run_sql(sql: str) -> str: ...
def policy(tool_name, tool_input):
sql = tool_input.get("sql", "")
if tool_name == "run_sql" and sql.lstrip().upper().startswith("DELETE"):
return [Finding.fail("no_deletes", severity="CRITICAL", message="DELETE is not allowed")]
return []
agent = gated_agent(Agent(name="assistant", tools=[run_sql]), policy)
gated_agent returns a copy of the agent with a Recusal tool input guardrail on every
function tool. A refused call's output is Recusal's reason, which the model reads on its
next turn. The tool does not run. A policy that raises refuses the call (fail closed).
Runner.run, Runner.run_streamed and a human approval (needs_approval) all pass
through the guardrail, which runs when the tool is about to execute, after any approval.
Under RunConfig(tool_execution=ToolExecutionConfig(pre_approval_tool_input_guardrails=True))
the SDK runs the guardrail before it asks a person as well, so such a call is judged
twice: once before the approval and once when it is about to run.
The gate judges the arguments as the SDK prepares them from the tool's schema: validated,
types converted ({"amount": "50"} reaches an int parameter as 50) and defaults
filled, each under the name of the parameter that receives it. Which parameter is the
context the SDK fills itself is read from the SDK's own schema for the tool. An allowed
call's prepared arguments are pinned on the tool context, so the SDK runs what was judged.
A sub-agent behind agent.as_tool(...) is called like a function tool, and the parent's
policy judges the input the sub-agent is given. With the default as_tool that is the
arguments as the model wrote them, {"input": "..."}. With as_tool(parameters=Model)
it is what the SDK's own adapter for that model makes of them: validated, types
converted ({"rows": "9"} reaches the sub-agent as 9), defaults filled, and a key the
model does not name dropped. Arguments the model does not accept are refused before the
policy runs. The sub-agent's own tool calls are judged by the sub-agent's gate, which
gate_tools requires.
Build the agent completely, then gate it. A tool appended to the gated agent's list
afterwards is not gated. The gated copy has its own tools, handoffs and mcp_servers
lists, so a handoff or a server added to the original agent after gating is not the
copy's. gate_tools(tools, policy) gates a list of tools directly.
Parameter types
Declare data-only parameters. These are gated and judged by value:
str, int, float, bool, None, Optional[...] and unions of these;
Literal[...] of strings, integers and booleans;
list[...] and dict[str, ...] of the above, a dict keyed by a Literal of strings
(dict[Literal["a", "b"], int]), and Any (judged as the JSON it was sent as);
- any of them with
Field limits such as ge=, le= or max_length=;
- any of them with a default that is JSON data, or with
Field(default_factory=list) or
Field(default_factory=dict).
A dict parameter needs function_tool(..., strict_mode=False): under the SDK's default
strict schema the SDK itself refuses to build such a tool (UserError,
"additionalProperties should not be set").
gate_tools and gated_agent raise TypeError, naming the tool and the parameter, for a
parameter no call to which could be judged:
- a type or a validation the SDK prepares only by running code of the tool's own: an
Enum, a Pydantic model, a dataclass, a TypedDict, datetime and date, tuple,
set, Sequence[...] and Iterable[...], bytes, Field(pattern=...) and a custom
validator. Take a str, an int, a list or a dict in its place and build the
application type inside the tool body;
- a default factory other than
list or dict (Field(default_factory=lambda: [...])).
Use a plain default and build the value inside the tool body;
- a default that is not JSON data (
tags: list[str] = (), timeout: float = math.inf).
Give it a JSON default: None, a string, a finite number, a boolean, a list or a dict;
- a mapping whose key type is neither
str nor a Literal of strings (dict[int, str],
dict[Literal[1, 2], str]). The SDK converts the keys of the JSON object the model
sends, and the gate judges arguments as JSON data, whose keys are strings. Declare
dict[str, ...] and convert the keys inside the tool body.
Put every decision on the record
from recusal.audit import AuditLog
from recusal_openai_agents import audited_agent
log = AuditLog(path="decisions.jsonl")
agent = audited_agent(Agent(name="assistant", tools=[run_sql]), policy, log)
audited_tools(tools, policy, log) is the list form. Each call a guardrail sees, allowed
or refused, is one hash-chained entry labeled openai_agents.tool_input_guardrail with
the SDK's tool call id and a SHA-256 fingerprint of the arguments (never the arguments).
If the log cannot be written the call is refused. Check the log with
recusal audit verify decisions.jsonl.
The audited forms are the plain ones with a recording passed in, so there is one decision
path: a call the audited gate refuses, the plain gate refuses, for the same cause.
A call that waits for a person's approval is judged, and recorded, when it is about to
run, so a call a person rejected is not on the log. The exception is the SDK option
pre_approval_tool_input_guardrails=True (above): the gate then runs before the approval
as well, so a call has an entry before a person decides, a rejected call keeps that one
entry, and an approved call has two entries under the same call id.
What the gate refuses, and what it does not see
gated_agent raises ValueError at construction for an agent that can run something the
guardrail never sees. The rule is default-deny:
- MCP servers attached with
mcp_servers=, and handoffs to other agents. For MCP
servers use
recusal-openai-agents-mcp.
- An agent with a
prompt. A prompt stored on OpenAI's servers can configure tools
that are not in the agent's tools list. Put the instructions and the tools on the
agent itself.
- An agent whose
model_settings can put tools into the request. extra_body or
extra_args with a tools, prompt, plugins, web_search_options or mcp_servers
key is refused. The SDK merges extra_body into the body of every model request: a
tools key there replaces the agent's own tool list in the request, and each of the
other four is sent beside it. extra_args are passed as arguments of the request call:
a prompt there is sent with a Responses request, and a tools key makes the SDK's
OpenAI models raise TypeError before anything is sent. Put the tools on the agent
itself.
Agent subclasses such as SandboxAgent and RealtimeAgent: a subclass can add
tools of its own at run time.
- Function tools that share a name. Two tools under one name are resolved by the SDK
last-wins. Two tools under one name in different
tool_namespace groups both run, but
the policy and the audit record are given the tool's own name without the namespace
and could not tell them apart. Give every function tool a unique name.
gate_tools and gated_agent raise TypeError, naming the tool, for a tool the
guardrail cannot judge: