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.15.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[...]anddict[str, ...]of the above, adictkeyed by aLiteralof strings (dict[Literal["a", "b"], int]), andAny(judged as the JSON it was sent as);- any of them with
Fieldlimits such asge=,le=ormax_length=; - any of them with a default that is JSON data, or with
Field(default_factory=list)orField(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, aTypedDict,datetimeanddate,tuple,set,Sequence[...]andIterable[...],bytes,Field(pattern=...)and a custom validator. Take astr, anint, alistor adictin its place and build the application type inside the tool body; - a default factory other than
listordict(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
strnor aLiteralof 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. Declaredict[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 userecusal-openai-agents-mcp. - An agent with a
prompt. A prompt stored on OpenAI's servers can configure tools that are not in the agent'stoolslist. Put the instructions and the tools on the agent itself. - An agent whose
model_settingscan put tools into the request.extra_bodyorextra_argswith atools,prompt,plugins,web_search_optionsormcp_serverskey is refused. The SDK mergesextra_bodyinto the body of every model request: atoolskey there replaces the agent's own tool list in the request, and each of the other four is sent beside it.extra_argsare passed as arguments of the request call: apromptthere is sent with a Responses request, and atoolskey makes the SDK's OpenAI models raiseTypeErrorbefore anything is sent. Put the tools on the agent itself. Agentsubclasses such asSandboxAgentandRealtimeAgent: 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_namespacegroups 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:
- Any tool that is not a
FunctionTool: hosted tools that run on OpenAI's servers (web search, file search, code interpreter, image generation, hosted MCP, tool search) and local ones the SDK executes itself (shell, apply patch, computer, custom). A tool type added in a later SDK release is refused too. The experimental Codex tool is refused as well: it runs its own commands. - A
FunctionToolbuilt by hand (FunctionTool(..., on_invoke_tool=...)). The gate could judge only the model's raw JSON, not what your invoker makes of it. Build the tool withfunction_tool. - A parameter outside the data-only set listed under Parameter types above: its type, its default, or the key type of a mapping.
- A variadic parameter (
*args,**kwargs). Its values have no names to judge by. Declare each parameter by name. - A wrapped function whose wrapper takes other parameters than the function. The SDK
reads a
functools.wrapsdecorator as the function it wraps. A wrapper that adds a parameter of its own (dry_run=False) would run it at a default that is in no schema, and one that takes some of the function's parameters, or takes them in another order, would hand the function other values than the policy judged. Two kinds of wrapper are gated: one that forwards*args, **kwargsand names no parameter, and one that takes exactly the function's parameters, by the same names, in the same order and of the same kinds. So is a stack of them, each level read in turn. A stack of more than 31 wrappers, or more than eightfunctools.lru_cachelayers one on another, is refused as more than the gate reads. A function with a declared__signature__is refused. - A decorator whose signature cannot be read. A class-based decorator that is also a
descriptor (
cachetools.cached,cachetools.func.ttl_cache,cachetools.func.lru_cache) hides the functions under it from inspection. Call the decorated function from a plain function and register that.functools.lru_cacheandfunctools.cacheare read through and gated. - A
functools.singledispatchfunction with an implementation registered, or asingledispatchmethod. The implementation that runs is chosen by the type of an argument, and each one has its own parameters and defaults. Register one plain function and dispatch inside its body. The dispatcher is found wherever it stands among the callables the call reaches: as the tool itself, as a method or a class method (function_tool(service.handle)), and underfunctools.wrapswrappers orfunctools.lru_cache. Asingledispatchfunction with nothing registered is the function it wraps, and is gated in each of those places; an implementation registered after the tool was gated refuses its next call in a later model turn, but not in the same turn: the SDK checks every call of a turn before any tool body runs, so an implementation one call of a turn registers runs, unjudged, for a later call of that turn. This is open; until it is closed, do not register implementations of a dispatcher that is a tool while an agent runs. A wrapper that only carries a copy of a dispatcher's attributes, and a callable object that happens to have adispatchmethod and aregistryattribute, are not taken for one. - A sub-agent behind
agent.as_tool(...)whose own tools are not gated. Gate the sub-agent first,gated_agent(sub, policy).as_tool(...), and the parent accepts it. - An agent tool whose
parameterstype is not a data-only Pydantic model. The gate works out what the sub-agent is given with the SDK's adapter for that type, and the SDK then validates the arguments again itself, so the two agree only for a model the SDK's own rule for data-only validation admits (can_prepare_without_user_code) and that is written out with no code of its own. The refusal names the field and its pydantic core type. Refused, with what to declare in its place:- a
date,datetime,timeortimedeltafield, aUUID, aPath, anAnyUrl, aDecimal,bytes: astr(or afloatfor theDecimal), read inside the sub-agent's own tools; - a
tuple, aset, afrozenset, aSequence[str]: alist; - an
Enum: aLiteralof its values; - a nested model, a model that refers to itself, a dataclass: flat fields;
- a field with a pattern, a validator, a serializer, a computed field, or
Field(exclude_if=...)(the SDK runs that callable again when it writes the input out): plain fields, checked inside the sub-agent's own tools; - a default that is not JSON data (
tags: list[str] = ()) and a default factory other thanlistordict: a JSON default, orField(default_factory=list); - a model with a
PrivateAttr, and one built withdefer_build=True: neither.
- a
Refused call by call, before the policy runs, with a reason the model reads:
- arguments that are not a JSON object, or that do not validate against the tool's
parameters (for an agent tool, against its
parametersmodel); - a non-finite number (
NaN,Infinity, a literal too large for a float, or a string afloatparameter reads as one). It is not JSON data: a policy cannot compare it and a record cannot fingerprint it; - arguments given to a tool that takes none;
- arguments that hold a value more than 64 levels below the arguments object. The limit is the gate's own and fixed: it is the same with and without an audit log, and does not move with the interpreter's recursion limit.
What the gate does not see:
- What a wrapper or the tool body does with the arguments. The gate judges the values the function is called with. A decorator that changes them in its body, and anything the tool reads from elsewhere, is not seen.
- A function a wrapper holds some other way than
__wrapped__. The gate reads the function, what its__wrapped__chain leads to, a bound method's function and a callable object's__call__. A decorator that applies a second decorator inside itself and calls that one (the inner wrapper sits in a closure, andfunctools.wrapspoints past it), or a callable object that copies another function's__wrapped__, runs a wrapper the gate never read. A parameter that wrapper takes or adds is not judged. - Model settings given to a run. Only the agent's own
model_settingsare read when it is gated.RunConfig(model_settings=...)is merged in when a run starts, and anextra_bodythere is not seen. - Legacy
functionsdefinitions inextra_body. Afunctionskey there is sent in the body of the request and is not refused. It only describes functions to the model: the SDK runs a call by looking its name up among the agent's own tools, so a call to a name that is not one of them raisesModelBehaviorErrorand nothing runs, and a call to a name that is one passes through that tool's guardrail. - A call the SDK rejects before the guardrail runs. For each of these the tool does
not run and the call is not on the audit log. These raise inside the SDK and stop the
run: a tool call id the model reuses for another call, within one response or in a
later turn, and a blank tool call id (
ModelBehaviorError); arguments that hold a lone surrogate character (UnicodeEncodeError); and arguments nested about a thousand levels deep or more (RecursionError, at a depth that depends on the interpreter's recursion limit). A tool the agent does not have raisesModelBehaviorErrortoo, unless the run is givenRunConfig(tool_not_found_behavior="return_error_to_model"), under which the model reads the SDK's "not found" error and the run goes on. A call the model repeats under the id and with the arguments of a call that already ran is not run a second time by the SDK, and is not judged a second time. - An error of the interpreter inside the guardrail. Under a recursion limit too small
for the guardrail's own walk over the arguments it raises
RecursionError. The SDK then stops the run with an error, the tool does not run, and there is no entry. - A realtime session.
gated_agentrefuses aRealtimeAgent.gate_toolsaccepts a list of function tools whatever they are attached to, but a realtime session runs the guardrail on a tool context of its own, so the arguments the gate pinned are not the ones that session executes, and this package has no test of a realtime session.
Status
In-depth review under way. Its fixes so far are released in 0.2.0, and the review continues. Recusal is a Beta (0.x) open-source project in active
development: it is not a finished or certified security product, and it is provided under
Apache-2.0 without warranty.
What the reviews are, and where every adapter stands.
Open from the latest review round, not yet fixed, stated so you can judge them:
- A
functools.singledispatchtool with nothing registered is accepted, and an implementation registered during a model turn runs unjudged for a later call of the same turn (see the bullet on single dispatch above). The fix decided is to refuse every single-dispatch function as a tool. - A dispatcher that is a callable object's
__call__, under afunctools.wrapswrapper, is not found; and a dispatcher is recognised by one code object read at import, so afterimportlib.reload(functools)a new one is not recognised.
Help make it better. Read the code, test this adapter against your own stack and tell us what you find. Reviews, bug reports and pull requests are all welcome: how to contribute, open issues. Please report a security gap privately, not in a public issue.
Compatibility
This package is outside the kernel's frozen perimeter (STABILITY.md, Integrations). Its
public names are the ones in recusal_openai_agents.__all__. When an SDK release changes
what the guardrail is handed, this package gets a release and the kernel does not.
A runnable offline demonstration, with the SDK's scripted model and no API key, is
examples/openai_agents_gate.py
and
examples/openai_agents_audit.py.
More
An arrow means "depends on". No arrow leaves the kernel, so a framework's breaking change is answered by a release of that framework's adapter, not by a release of the kernel.
- Framework notes for the OpenAI Agents SDK: the detail behind this page.
- All eight adapter packages and the kernel, which has zero runtime dependencies.
- Verifying a release: each release is built in CI, signed with Sigstore and published to PyPI by trusted publishing.
- Changelog, issues, security policy and support.
Licensed under Apache-2.0.
Metadata
Release files for recusal-openai-agents 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| recusal_openai_agents-0.2.0.tar.gz | 31.6 kB | With provenance | Details for recusal_openai_agents-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| recusal_openai_agents-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for recusal_openai_agents-0.2.0-py3-none-any.whl |
Total release size: 63.4 kB
Release files / recusal_openai_agents-0.2.0.tar.gz
| Download URL | recusal_openai_agents-0.2.0.tar.gz |
|---|---|
| Size | 31.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a664d553f3f70b29f4ef36701a68ae63af57fb99befdcda9b66c61a0bb2ff017
|
|
BLAKE2b-256 checksum How to use checksums |
f2f3204699933ff7df265f7117cb80342a53b11d3976779f08a4fc584fce9ff6
|
| 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 Nov 23, 2026.
Transparency logRelease files / recusal_openai_agents-0.2.0-py3-none-any.whl
| Download URL | recusal_openai_agents-0.2.0-py3-none-any.whl |
|---|---|
| Size | 31.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c4c200eab7107e04c967fb1ffd396fb311f2ae3e5ba6781a0bb5156dabfed3f2
|
|
BLAKE2b-256 checksum How to use checksums |
c04e68113952cb1efc41ca361493bd4c42855bcabba3001c4dfd44cba67a9e7f
|
| 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 Nov 23, 2026.
Transparency logSecurity for recusal-openai-agents 0.2.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.
Attestation for recusal_openai_agents-0.2.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 Nov 23, 2026.
Transparency logA 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.