Skip to main content

recusal, deterministic governance for AI agents

recusal-pydantic-ai

Website PyPI CI OpenSSF Scorecard python license

The Recusal gate for Pydantic AI: every 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.

Before the tool runs. An agent proposes a tool call. Recusal, your policy with no model in it, decides. With no objection the tool runs. On a failing finding, or when the policy itself raises, the call is refused: the tool never runs and the reason goes back to the model. Every decision can be written to a hash-chained audit log, if you pass one.

This is a separate distribution from recusal. The kernel has zero runtime dependencies and a frozen compatibility perimeter; this package carries the Pydantic AI dependency and its own version, so a Pydantic AI release never forces a release of the kernel.

Install it from PyPI:

pip install recusal-pydantic-ai

Requires Python 3.11+ (Pydantic AI's minimum), recusal>=0.17.1 and pydantic-ai-slim>=2.67.0. It is tested on every pull request against exactly pydantic-ai-slim==2.67.0, and weekly against the newest release. From 0.2.2 the floor is recusal 0.17.1, whose walk refuses a wrapper a decorator holds whose chain of __wrapped__ comes back on itself: beside 0.17.0, which 0.2.1 allowed, such a held wrapper with a dry_run=False of its own ran it, judged without it. The refusal messages of 0.17.1 no longer advise calling the refused function from a plain function, and the reasons this gate gives after the kernel's words rely on that. From 0.2.1 the floor was recusal 0.17.0, whose walk refuses a weakref.proxy on the way and a single-dispatch function with nothing registered: beside 0.16.0, which 0.2.0 allowed, both ran a value no policy judged. See "Refused although it runs correctly" below for what each floor costs.

The package ships inline types (py.typed) for your editor and type checker. From 0.1.2 every function signature in it is annotated.

Use

from pydantic_ai import Agent
from recusal import Finding
from recusal_pydantic_ai import RecusalGate


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 = Agent(model, tools=[run_sql], capabilities=[RecusalGate(policy)])

A refused call is answered to the model as a failed tool result carrying Recusal's reason. The tool does not run and no retry budget is spent. A policy that raises refuses the call (fail closed).

RecusalGate declares Pydantic AI's innermost position, so its hooks run after every ordinary capability's. List it directly and last. The gate reads the order the run dispatches in, and a call is refused when a capability with a before_tool_execute of yours comes after the gate, since it could change the arguments the gate judged. That happens in two ways: another innermost capability listed after the gate, and a gate placed inside a WrapperCapability, which does not pass the gate's position on. The same holds for output functions and before_output_process. A hook bundled before the gate, in the same list or behind the same wrapper, runs before it and is not refused.

A decorated tool must be transparent. Python fills a default in when a function is called, after every hook, and a decorated tool is several functions: Pydantic AI builds the tool's schema from the innermost one and calls the outermost. Its validation fills in the innermost function's defaults, so the policy sees those. A wrapper on the way that has a parameter of its own is read by nothing, and whether its value reaches the function under it depends on the wrapper's body, which cannot be read. So all four forms of the gate (the two capabilities and the two hook functions) read the stack from the callable Pydantic AI calls down to the innermost function, as Python hands the call on (a wrapper's __wrapped__, a bound method's function, a callable object's __call__, the function of a functools.partial, whatever __wrapped__ the partial itself carries), and each wrapper on it must be one of these (the wrappers under a functools.partial that binds keywords are held to this twice, as the partial shows them and as they are written, because a partial with a keyword shows every later parameter as keyword-only and would make a wrapper that takes a parameter as another kind than the function look like one that restates it):

  • it takes only *args and **kwargs (a logging, timing, tracing or retry decorator that passes everything through);
  • it restates the function's own named parameters: the same names, kinds and order, each with no default or the function's own default. It has a fixed signature, or it also restates the function's **extra under the same name; the second only over a function that takes no *args and no positional-only parameter;
  • it forwards **kwargs and also names parameters (def wrapper(table, **kwargs)), where a wrapper that kept one would fail the call, and where binding by name and by position cannot differ. Each parameter it names is of the same kind as in the function and has no default on either side; the positional ones are the function's first parameters, in the function's order; and the function takes no *args and no positional-only parameter, since Pydantic AI passes such a function's values by position. Such a wrapper may forward *args as well (def wrapper(table, *args, **kwargs)) only while no wrapper above it on the stack names more positional parameters than it does: one above could pass them on by position. A wrapper under it that names more does not count.

For a tool that takes the run context, a wrapper's first positional parameter is the context, whatever the wrapper calls it (def wrapper(context, *args, **kwargs)), unless it has the name of another parameter of the function. The context counts as the function's first parameter in these rules, so a wrapper that names it and forwards is refused over a function that takes *args or a positional-only parameter after the context. A logging wrapper of that form above one that restates the function's parameters is an ordinary pair and is not refused; under it, it is.

Anything else is refused before the policy runs, with a reason that says what the wrapper does and names the parameter: a wrapper with a keyword of its own (def wrapper(*args, retries=3, **kwargs)), a parameter it takes as another kind than the function does (def wrapper(*args, table, **kwargs) over def f(table, limit=10) takes table keyword-only), a default that differs from the function's, a parameter left out or reordered. Give such a wrapper its setting when it is built (@retrying(times=3)) and not as a parameter of the wrapper itself. The wrapper beartype generates has keywords of its own and is refused by this rule: register a plain function in its place, as below.

A plain function in its place. Where this page or a refusal says to register a plain function in place of what was refused, the gate judges that function's parameters and does not read its body or what it calls. So give it the parameters of the function that does the work (the innermost one, under every decorator), with the same defaults, and have it call that function directly, not the decorated one: what a decorator did is then the plain function's to do in its body. A plain function that calls the decorated stack instead runs whatever the stack fills in itself, unjudged: a decorator that holds a wrapper with dry_run=False of its own runs that default, and where the decorator fixes dry_run itself, a plain function that passes dry_run on as well makes the call fail with a second value for it. Where a remedy is named that the gate reads (register the function itself, functools.update_wrapper(self, fn), delete a declared signature, bind by keyword), prefer it. Also refused:

  • A callable that declares a signature of its own: a __signature__, a __text_signature__ that is not the interpreter's, or an object that shows a __code__ while a call runs its __call__. inspect.signature can read each in place of the parameters Python binds, so those cannot be read. The reason names which of the three was found (before 0.2.1 it named __signature__ for all three). The decorators the decorator library builds do this, and so does Pydantic AI's own tavily_search_tool when it is given a search setting to fix (tavily_search_tool(client=client, include_domains=[...])). Build that tool without the fixed setting and hold the model to the value in your policy, which is given each search argument the model can set, or call the Tavily client from a plain function of your own that has the fixed value in its body (that value is then not judged: it is your constant). Otherwise delete the declaration, so the parameters Python binds are read.
  • A decorator that cannot be inspected: a class-based decorator that is also a descriptor, such as cachetools.cached, a functools.lru_cache or functools.cache wrapper under a functools.partial, or a stack deeper than the kernel's walk reads. The walk reads the tool and at most 31 callables after it: a function decorator is one, and a class-based decorator built with functools.update_wrapper is two (what it names as __wrapped__ and its own __call__). So under one function wrapper a stack is read 30 function decorators deep, or 15 class-based ones, and a deeper one is refused. Give a descriptor's class no __get__, take a cache out from under the partial, or shorten the stack; otherwise register a plain function in its place, as above. The reason for a descriptor says that cause (before 0.2.1 it said "cannot be inspected").
  • A callable object on the way whose __call__ takes *args or **kwargs and that names nothing it wraps. The kernel's walk passes through a callable object that names nothing as __wrapped__ and reads its __call__; what that __call__ hands the call to is not read. A class-based decorator that keeps the function in an attribute and answers every other attribute from it with __getattr__, over a functools.partial, on a tool that takes the run context, was judged {"table": "prod"} and ran the function's dry_run=True, which nothing showed: Pydantic AI took *args for the context and the model's keys into **kwargs. In 0.2.0 too. Every level of the walk is asked, so the same object is refused under a functools.partial, as what a cache named again for another function calls, and behind the __wrapped__ that a tool which is a functools.partial carries, along a chain of such names to its end. An object names what it wraps where it holds a __wrapped__ that is not None, read without __getattr__: in its own dictionary, as a plain attribute of its class, in a slot that is set, or from a property. A __wrapped__ slot that is declared and never set names nothing (a lookup on the object then falls to __getattr__), and such an object is refused too. Give the object a __wrapped__ that names what it calls (functools.update_wrapper(self, fn) in its __init__). Where that is a functools.partial of an annotated function, give the partial the function's annotations too (p.__annotations__ = dict(f.__annotations__)), or Pydantic AI cannot build the tool. Otherwise register a plain function in its place, as above.
  • A weakref.proxy, as the tool or anywhere on the way to the function. A proxy shows the attributes and the class of the object it stands for and is not that object, so what a call to it runs cannot be told: beside recusal 0.16.0 a proxy of a class-based decorator whose __call__ takes the tool's two parameters swapped ran them swapped, one whose __call__ has a dry_run=False of its own ran it, and a proxy of a cache named again over a wrapper with a parameter of its own ran that parameter at its default. Refused with a reason that says so. Register the function itself, not a proxy of it.
  • A callable that answers for another object. The ordinary case is a class-based decorator that keeps the function in an attribute (self.fn = fn) and answers every other attribute from it with __getattr__: over a function that names a __wrapped__ of its own (any functools.wraps decorator, any functools.lru_cache) it answers __wrapped__ with what that function wraps, and the walk would step past the function it calls. Also an object whose __class__ is not its type, where it holds no __wrapped__ of its own or its own __call__ takes parameters by name. The reason passes on what the kernel found. Call functools.update_wrapper(self, fn) in the decorator's __init__ and it is read to the end; otherwise register a plain function in its place, as above.
  • A decorator that holds a second wrapper of the function. A decorator that applies another functools.wraps wrapper of the same function inside itself and calls that one, from its closure, by a module global it names, from a class-based decorator's instance, or by way of a class-based decorator, a callable object, a functools.partial that carries a __wrapped__, a weak proxy, a cache named again or a second held wrapper: functools.wraps points past the inner wrapper, so it is not read like one applied directly. Refused where the inner wrapper takes a parameter of its own, and where it takes the tool's parameters in another order (beside recusal 0.16.0 one that took them swapped ran them swapped: judged sql='', force=True; ran sql=True, force=''). The reason names the parameters. Refused too, since recusal 0.17.1, where a callable the decorator holds names a chain of __wrapped__ that comes back on itself, which 0.17.0 read as reaching nothing: one with a dry_run=False of its own ran it, judged without it. Register a plain function in its place, as above. Not found, by design of the kernel's walk: an inner wrapper held any other way, among them a plain function or a lambda that names nothing as __wrapped__, a callable object's __call__ that names nothing, a wrapper held in a container, a slot or a non-callable object, and a wrapper built on its first use (the 0.17.0 entry of the changelog lists them all, under "Still not found, by design").
  • A functools.partialmethod over a callable object: refused, with a reason that says so and what to do. Over a plain function the same partialmethod is read in full.
  • Four decorator shapes the kernel's walk reads through. A decorator written as functools.wraps(f)(functools.partial(helper, f)); @functools.wraps(f) above @functools.lru_cache above another wrapper (the cache names f and calls the wrapper); a class-based decorator written inside the decorator, whose __call__ calls a second wrapper the decorator built, or one at module level whose __call__ names that wrapper as a global; and a method that delegates to a free function under functools.wraps of it and keeps its object, where the free function's first parameter has a default. The kernel reads the second and the third like the same decorator written with a nested function, so a wrapper with a parameter of its own is refused, naming the parameter, and one that only passes its arguments on is accepted, whatever the cache calls. On a method with a positional parameter that has a default, the second is refused where the wrapper under the cache is itself a functools.wraps(fn) forwarder (@functools.wraps(fn) def wrapper(*args, **kwargs)): this gate counts it as a wrapper that names the method's parameters (see "The object of a bound method" below). The same forwarder written without functools.wraps (@functools.wraps(fn) @functools.lru_cache def wrapper(*args, **kwargs)) is read and runs as judged. This gate has a rule of its own for the first (a partial that binds by position and carries a name, see below), and refuses it. The kernel's walk refuses the fourth (BoundArgumentKept), and since recusal 0.17.1 also where that first parameter has no default and the tool takes a parameter that is not keyword-only. Not found: a wrapper that takes the bound object under the same name as the first parameter of the function it wraps and does not hand it on (see "A method whose decorators were written for free functions" below). A cache whose function cannot be told from what it refers to is refused, not read: apply the cache to the function itself. For the others, register a plain function in their place, as above.
  • A single-dispatch function (functools.singledispatch, or the callable a singledispatchmethod hands out). With an implementation registered beside its base one, or in its place (register(object)), the implementation that runs is chosen at call time, by the type of an argument, so its parameters and defaults cannot be read. With nothing registered but its base, an implementation can be registered on it at any moment, also between the check and the call: beside recusal 0.16.0 a wrapper that registered one on its first use ran its purge=True for the very call that was judged without it. Both are refused, each with a reason of its own. Register one plain function as the tool, declaring every parameter any implementation takes, and branch on the type inside its body: a single-dispatch function called from a plain function is not read, so an implementation registered later runs there with defaults no policy saw (before 0.2.1 the reason said to call the dispatcher from a plain function, which does exactly that). A function that only has attributes called registry and dispatch is not taken for one. (Pydantic AI cannot run a functools.singledispatchmethod as a tool built from its signature. Given its schema by hand, one is refused by this rule.)
  • A functools.partial that binds a value by position over a wrapper that names a parameter. The partial's own signature, which is what Pydantic AI and the gate read, drops the leading parameter of every wrapper under it, and that parameter's default with it: functools.partial(scoped(default_table(purge)), "acme") with def wrapper(tenant, *args, **kwargs) over def wrapper(table="archive", *, limit=100) looks like a stack that names nothing, and ran table="archive" with the policy handed {"limit": 5}. The gate does not reason about what such a wrapper's body would do. Under a partial that binds by position there may be only wrappers that take nothing but *args and **kwargs (and other partials); a wrapper there that names any parameter of its own, of any kind and name, with or without a default, the run context included, refuses the call, whether or not a body that kept the value would fail. So functools.partial(scoped(purge), "acme") is refused for any scoped whose wrapper names tenant. Bind the value by keyword, or register a plain function in its place, as above. A value bound by position directly over the function, or over wrappers that only forward, is read as the function's leading parameter and is not refused. A value a functools.partial binds by position is not shown to the policy: it is your application's constant, not the model's, and the policy is handed the parameters left to the model. functools.partial(plain, "fixed") over def plain(table, limit=10) is judged as {"limit": 10} and runs table="fixed". (The tool is handed the dict the policy judged, and with table in it the call would fail on a second value for table.) A value it binds by keyword is the default of the parameter it names, and is shown and judged, as below. Write a policy that needs the bound value against a plain function that takes it as a parameter, or bind it by keyword. A name the model sends that the function the tool shows does not take, and that a callable on the way takes for a value it gets otherwise, is refused: a parameter the partial fills by position, the run context's name (ctx), the object of a bound method or a classmethod under whatever name the function or a wrapper on the way gives it (self, svc, cls). Where the function takes **kwargs, Pydantic AI accepts such a name, and the call fails on a second value for the parameter; before 0.2.1 the TypeError left the run as an exception. Two more refusals of such a partial: one that was named with functools.update_wrapper or functools.wraps (see the next point), and one that binds a positional-only parameter of a function that also takes **kwargs (functools.partial(fetch, "acme") over def fetch(tenant, /, table, **extra)): an argument sent as tenant is not a duplicate to Python, it lands in **extra while the function runs the bound value.
  • A signature Pydantic AI reads that is not the function the call reaches. Pydantic AI validates the arguments against inspect.signature of the callable it is given, and decides from it which values to pass by position. That reading follows __wrapped__; the gate reads what Python binds. For every tool built from its signature the two must be the same parameters (names, kinds, order and defaults), or the call is refused. The case that differs is a partial named the standard-library way, functools.update_wrapper(functools.partial(insert, "acme"), insert): the signature is then the function's own, with the parameter the partial fills still in it, and insert(tenant, *rows) ran tenant="acme" with the model's tenant as its first row. A keyword partial named that way is refused too: Pydantic AI would show, and fill in, the function's default in place of the value the partial binds. Set __name__ and __qualname__ on the partial instead, or register a plain function in its place, as above.
  • The object of a bound method past a wrapper that names a positional parameter (def wrapper(self, *args, **kwargs)). The object is read as filling the function's leading parameter, and the wrapper may keep it. Refused where a wrapper that kept it might not fail the call: that parameter of the function has a default; the function takes *args or a positional-only parameter after it; or the values after it can be passed on by position and move up a place, with a default to fill the gap they leave. The last is counted: a wrapper on the stack that names positional parameters beyond the object can pass that many on by position (the run context of a context-taking tool is one such value, and so is a value a partial binds), and the call is refused when the last parameter of the function they reach has a default. A functools.lru_cache or functools.cache wrapper applied to the function it names keeps nothing and does not count as such a wrapper; one named again for another function (functools.wraps(f) above the cache) counts as the wrapper it calls, and where that wrapper is itself a functools.wraps(f) forwarder (def wrapper(*args, **kwargs)), as one that names the parameters of f. Before 0.2.1, in 0.2.0 too, it did not: a method decorated with functools.wraps(fn) above functools.lru_cache above def wrapper(self, table, limit=10): return fn(table, limit) was judged {"table": "t", "limit": 5} and ran self="t", table=5, limit=10. So a method decorator that restates the method's parameters (def wrapper(self, table, limit=10)) over a method with a positional parameter that has a default is refused. That refusal is conservative: no wrapper body that passes the object on can misuse such a stack, and it is the price of not reading bodies. An ordinary method decorator (def wrapper(self, *args, **kwargs)) over a method whose other parameters are named and not positional-only is not refused; under a cache named again it is, where it is a functools.wraps forwarder and a positional parameter of the method has a default.
  • A keyword a functools.partial binds that does not reach the parameter it names: functools.partial(fetch, limit=77) over def fetch(table, limit=10, /, **extra). Python does not bind a keyword to a positional-only parameter, so **extra takes the 77, limit runs on its own default, and the partial no longer shows limit at all. Refused when a keyword names a positional-only or variadic parameter of the function or of a wrapper under the partial.
  • A value for the function's *args that is not a list. Pydantic AI hands the function its items one by one, so a string would reach it letter by letter. Validation makes the value a list; another one reaches the gate only where a hook of yours skips validation (SkipToolValidation) or answers a validation error.

Refused although it runs correctly. The gate reads parameters, not bodies, so some tools that run as judged are refused, each with a reason that says what to write instead. New with 0.2.2, which requires recusal 0.17.1: the walk of 0.17.1 refuses these, and the walk of 0.17.0, beside which 0.2.1 can be installed, read them (each was checked through this gate: 0.2.1 beside 0.17.0 ran it as judged):

  • a method decorator whose wrapper takes the object under another name than the method has for it and hands it on (def wrapper(this, *args, **kwargs): return method(this, *args, **kwargs) over def find(self, query)), or takes it as self over the cls of a classmethod, where the tool takes a parameter that is not keyword-only: take the object under the name the method has for it and hand it on by position, where no other wrapper on the way keeps it (see "A method whose decorators were written for free functions"), and otherwise register the function itself;
  • a method decorator, or a method under functools.wraps(f), that hands its object on to a function that has another name for that place, by position or by keyword (return naming(self, *args, **kwargs) over def naming(owner, user), return fn(*args, owner=self, **kwargs) over def act(owner, table, **extra)), or that passes a value of its own in that place (return search(self.tenant, *args, **kwargs), or search(*args, tenant=self.tenant, **kwargs), over def search(tenant, query)), where that parameter has no default and the tool takes a parameter that is not keyword-only (0.17.0 refused these where it has one): register the function itself, with every parameter it takes;
  • a decorator that holds a callable whose chain of __wrapped__ comes back on itself (a helper with helper.__wrapped__ = helper, two helpers that name each other, an object or a functools.partial that names itself), whatever it runs: name the function it wraps, once.

New with 0.2.1, which requires recusal 0.17.0: the walk of 0.17.0 refuses these, and the walk of 0.16.0, beside which 0.2.0 can be installed, read them (the first two, and a single-dispatch function nothing is registered on, were checked through this gate: as it stood before 0.2.1, beside 0.16.0, it ran them as judged):

  • a weakref.proxy of a plain function, as the tool or anywhere on the way: register the function itself;
  • the class-based decorator above that keeps the function in an attribute and answers every other attribute with __getattr__, over a function that names a __wrapped__ (any functools.wraps decorator, any functools.lru_cache), and any other proxy that answers __wrapped__ only from __getattr__: call functools.update_wrapper(self, fn) in its __init__, or give it a __wrapped__ attribute that names what it calls. (Over a plain function such a decorator shows that function's __code__ and is refused as a declared signature, as it was before 0.2.1 under a reason that named __signature__);
  • an object whose __class__ is not its type, where it holds no __wrapped__ of its own, or holds one and its own __call__ takes parameters by name: register a plain function in its place, as above;
  • a single-dispatch function or method that nothing is ever registered on, as the tool, under a wrapper, or held by a wrapper: register one plain function that branches on the type, as above;
  • a decorator that holds a functools.wraps wrapper that takes the tool's parameters in another order and is called by keyword, or one that takes only a later parameter of the tool in the first place: give the held wrapper the tool's parameters in the tool's order, or by keyword only;
  • a decorator that holds a weakref.proxy of a callable the walk does not otherwise reach (a helper among them): hold the callable itself;
  • a decorator that holds a cache named again for another function, or one that names nothing, where the cache calls anything but a plain function on the way to the tool's function;
  • a decorator whose held values lead along a chain 32 callables long or more, or to more than 16,384 callables.

New with 0.2.1 by rules of this gate's own, found by the reviews of 0.2.1 before its release:

  • a callable object anywhere on the way whose __call__ takes *args or **kwargs, names nothing it wraps and passes every argument on (the forwarding class-based decorator above, over a functools.partial, under one, or called by a cache named again), also where the model sends every parameter and the call runs as judged: give the object a __wrapped__ (functools.update_wrapper(self, fn), and over a partial of an annotated function the function's annotations on the partial);
  • a method decorator named again above a cache (functools.wraps(fn) above functools.lru_cache) whose wrapper under the cache is itself a functools.wraps(fn) forwarder (def wrapper(*args, **kwargs)), over a method with a positional parameter that has a default: the gate counts that forwarder as a wrapper that names the method's parameters, as it counts one that restates them and hands the object on (the page said so of the second alone until 0.2.2). Write the forwarder under the cache without functools.wraps (@functools.wraps(fn) @functools.lru_cache def wrapper(*args, **kwargs)), or apply functools.lru_cache to the method itself: each is read and runs as judged.

Refused before 0.2.1 too, and still: a declared signature that matches the real parameters; a facade method that does hand its bound object on, where the parameter its object would fill has a default (BoundArgumentKept); a method decorator that restates the method's parameters over a method whose positional parameter has a default (see above); and every wrapper with a parameter of its own, whatever its body does with it. For each, register a plain function in its place, as above: it calls the innermost function directly, and the gate judges its parameters and does not read its body.

No longer refused in 0.2.1: a stack in which a functools.partial that binds nothing and is named with functools.update_wrapper stands under another wrapper (logged(functools.update_wrapper(functools.partial(f), f))), and functools.wraps(f) above functools.lru_cache above a wrapper of f that only passes its arguments on, which the gate before 0.2.1 refused as "cannot be inspected" beside recusal 0.17.0, and 0.16.0 too: it laid a walk of its own beside the kernel's and refused where the two counts differed. It now reads the callables the kernel's walk reads (reached_callables), and each such stack is read, or refused for what it is.

Defaults are judged. A default of the innermost function that the arguments leave out is added, judged, and passed to the function written out. For a tool built from its signature Pydantic AI's validation has already done that. A tool given its schema by hand (Tool.from_schema) is not validated, and a hook of yours can hand arguments in in place of validation (SkipToolValidation), so there the gate completes whatever was left out. A value a functools.partial binds by keyword is the default of the parameter it names. A class used as the tool function is completed from the signature Pydantic AI validates against, also behind a partial that binds keywords. Two more refusals follow from it:

  • A default that is not plain data (a logger, a client, a sentinel object) cannot be shown to a policy. For a tool given its schema by hand the refusal names the parameter. For a tool built from its signature Pydantic AI has already filled the default in, and the call is refused as carrying arguments that are not plain data. Give the parameter a JSON default or None and resolve the object inside the function. For a tool given its schema by hand, a positional-only parameter with a default that the model left out is refused too, since the default cannot be written out by name.
  • For a tool given its schema by hand, a function or a wrapper that takes *args or **kwargs: it can fill a value in in its own body, which cannot be read. The refusal says whether it is the function or a wrapper around it. The tools pydantic_ai.ext.langchain builds are of this kind. Give the function named parameters (in a wrapper, restate them), or build the tool from its signature.

A toolset runs after every capability hook, so one that runs other tools' calls itself could also change the arguments after the gate judged them. A run with one in its toolsets has every call refused:

  • a toolset of yours that holds other toolsets and has its own call_tool (a WrapperToolset subclass overriding it, or a container written from scratch, which would also hide what it holds). The gate looks for held toolsets in the toolset's attributes and four levels into the lists, tuples, sets, dicts and plain objects there, nearest first, and gives up after 4,000 values: a toolset with its own call_tool that it could not finish searching is refused as well. A toolset that only keeps a reference to another one, and never forwards to it, is refused by the same rule: keep such a reference outside the toolset;
  • a subclass of a Pydantic AI toolset that replaces its call_tool;
  • a toolset with a process_tool_call function, such as an MCP server given one.

The gate reads the run's toolset at the time of each call, so this holds for a wrapper another capability adds and for one a dynamic toolset (@agent.toolset) returns. Not refused: the toolsets Pydantic AI ships (prefixing, renaming, filtering, approval, tool search, durable execution), a subclass of one that leaves call_tool alone, and a toolset of your own that holds no other toolset: that one is the tool itself, and its body is yours, like a tool function's.

The same gate as a plain hook is Hooks(before_tool_execute=recusal_before_tool_execute(policy)). It judges tool calls only, not output functions or calls handed to the application, and Hooks declares no ordering: list it after every other capability, and use it only where no innermost capability is added, since one runs after it wherever it is listed. Prefer RecusalGate.

Output functions (output_type=fn) run the application's function with values the model chose, so RecusalGate judges them too, under the function's name, before they run: a dict (a multi-argument function's arguments, or a single dict argument) is judged as it is, any other single value as {"output": value}. A refusal asks the model again; the function does not run, and when the output retries run out the run ends with an error. Under run_stream Pydantic AI does not retry: a refusal ends the stream with UnexpectedModelBehavior ("retries are not supported in run_stream()"), and the refused function does not run. Plain structured output has no output function and is not judged.

  • The name is the function's __name__, and it is all the policy is given. A decorator that does not copy it (functools.wraps does) leaves its wrapper's name, so the function is judged as wrapper. A tool and an output function of one name are both judged under it: give an output function a name no tool has.
  • Two output functions with the same name (output_type=[review.submit, prod.submit]) are refused, each time the model picks one: Pydantic AI gives each its own output tool, and the policy could not tell which of them it was judging. A text output function (TextOutput) is refused when an output tool runs a function of its name. Give each output function a name of its own. One function listed twice is one function.
  • The data-only rule holds here too: an output function whose parameter is a Pydantic model, a dataclass or an Enum is refused. Declare plain fields (str, int, list, dict) and build the model inside the function.
  • A union of output functions under NativeOutput or PromptedOutput is refused: Pydantic AI does not tell the hook which of them it will call. Use tool output (the default), where each function is its own output tool and is judged by name.
  • A Choices output is judged as choice with {"choice": key, "set": name} when the pick is final, name being the set's (Choices(..., name=...), "Choices" by default). Pydantic AI calls the picked value when it is callable, and the hook is handed the key and not the values, so a pick is judged with or without an action. Inside a NativeOutput or PromptedOutput union Pydantic AI does not call the action, and the pick is not judged.
  • With run_stream, Pydantic AI runs an output function on partial output as it arrives; each of those calls is judged, so one answer can have several decisions.

Calls handed to the application (an ExternalToolset, a tool that raises CallDeferred) are judged before they leave the run, as the model sent them, which is what the application receives: no defaults are filled in and no types converted, so write the policy for such a tool against the JSON. A refused call is answered with the refusal, which the model reads; an allowed one is handed on as the model sent it, which is what was judged. A call with no arguments (the model sent none, or the empty string) is judged as {} and handed on as the model sent it, None or ''. A call waiting for approval is judged when it runs, with the arguments it runs with, an approver's overrides included.

To answer deferred calls inside the run, give the handler to the gate:

agent = Agent(model, toolsets=[external], capabilities=[RecusalGate(policy, deferred=handler)])

handler(ctx, requests) is the function HandleDeferredToolCalls takes. The gate judges the calls first and calls it with the ones it allowed. Pydantic AI offers deferred calls to each capability in turn and the gate comes last, so a handler in any other capability (HandleDeferredToolCalls, a Hooks with a deferred hook, or one of your own) would be handed calls no policy has judged: a run with one is refused with a UserError that says this, before the run starts, so also when a run is resumed from a history that ends in a tool call.

Tools the provider runs (web search, code execution, web fetch, a provider-side MCP server and the like) run with arguments the model chose where no hook of your application sees them. A gated agent that offers one is refused with a UserError before the request is sent, as is one whose model settings switch such a tool on (openai_native_tools, or tools, plugins, web_search_options, mcp_servers or search_parameters in extra_body), on the run or on the model. The gate asks the model what the request will carry, and each candidate of a FallbackModel in turn, so a tool the model drops, or replaces with its local version (WebSearch, WebFetch and MCP on a model without the provider side), is not refused; where the provider side would be used, turn it off with native=False. Provider-side tool search is allowed: it finds tools, and the calls to them are judged like any other.

Realtime sessions (agent.realtime(...).session()) are refused with a UserError when they start: a session calls none of the request and output hooks the gate judges in.

The name the policy is given is the one the model calls the tool by: under a PrefixedToolset or RenamedToolset that is the prefixed or new name (db_wipe for a tool wipe under the prefix db), so write the policy for the names you configured.

Put every decision on the record

from recusal.audit import AuditLog
from recusal_pydantic_ai import RecusalAuditedGate

log = AuditLog(path="decisions.jsonl")
agent = Agent(model, tools=[run_sql], capabilities=[RecusalAuditedGate(policy, log=log)])

Each decision the gate makes, allowed or refused, is one hash-chained entry labeled with the hook that made it: pydantic_ai.before_tool_execute for a tool call, pydantic_ai.before_output_process for an output function or a Choices pick and pydantic_ai.handle_deferred_tool_calls for a call handed to the application. Each carries Pydantic AI'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 gate calls the plain gate's own refusal function, so there is one decision path.

What the gate does not see

  • Capabilities an override puts in its place. agent.override(spec=...) with a spec that names capabilities replaces the agent's own, the gate with them; is_gated(agent) reads the capabilities in effect, so it is False there.
  • A gate that is not loaded. Pydantic AI runs no hook of a capability loaded on demand until it is loaded. RecusalGate(..., defer_loading=True) is refused when it is built, and a gate inside a group loaded on demand does not count for is_gated. List the gate directly.
  • is_gated reads the capabilities as listed. For a gate a capability function returns (lambda ctx: RecusalGate(...)), or one inside a WrapperCapability, it says False although the gate runs.
  • A toolset of yours that reaches another toolset through a function. One that builds or fetches the toolset it forwards to inside call_tool (a factory, a closure) holds nothing the gate can find, so it is taken for the tool itself: the policy judged the arguments it was handed, and what it does with them is its own code.
  • A WebRTC offer answered for the browser. answer_webrtc_offer() hands the provider the agent's tool list without starting a run, so no hook runs and nothing is refused there. No tool of yours runs from it either: that takes a session, which is refused.
  • A provider tool switched on some other way. The settings named above are the ones the gate knows. A model that searches or runs code by itself, or a setting not listed, is not seen.
  • Whoever reads the event stream. Pydantic AI emits a tool call as an event before the call is judged. Code that acts on that event, instead of on the tool running or on the deferred request it is handed, acts before the gate.
  • A wrapper toolset under a run context with no tool manager. The gate reads the run's toolset from RunContext.tool_manager at the time of each call. Where Pydantic AI provides none (its Temporal activity context), the gate relies on the check it makes when the run's toolsets are assembled, which does not see a wrapper another capability adds afterwards or one a dynamic toolset returns. It finds the function a tool runs, and a run's output functions, the same way, so there it completes no defaults, reads no wrappers and does not see two output functions of one name either.
  • What a function does in its own body. A value a function sets itself, a wrapper that restates the function's parameters and then does not pass one on (the function runs on its own default for it, or on the value a partial under the wrapper binds; or, where the wrapper passes the others on by position, each of those reaches the parameter before its own), a function that calls a single-dispatch function, and a decorator that applies another decorator inside itself where the kernel's walk does not find the inner one (see "A decorator that holds a second wrapper" above): the policy judged the arguments, and what the code does with them is its own.
  • What a class used as a tool function does when it is built. The gate reads the signature Pydantic AI validates the class against and completes the arguments from it. It does not read __init__, __new__ or a metaclass themselves, so none of these is seen: a decorator on one of them with a parameter of its own; a __new__ that shows fewer parameters than __init__ (def __new__(cls, table, **kwargs) beside def __init__(self, table, force=False, **kwargs) is judged without force); a declared __signature__ that leaves a defaulted parameter of __init__ out; a metaclass __call__ that takes other parameters than __init__ does.
  • A method whose decorators were written for free functions. For a bound method the object is read as filling the leading parameter of the function, and the rules above assume each wrapper under it takes the object first, as def wrapper(self, *args, **kwargs) does. A method without self under a decorator that takes the object under the very name the function has for that place and does not hand it on is not told apart from one that does: class Repo with @scoped @default_table def purge(table, *, limit=100), where scoped has def wrapper(table, *args, **kwargs): return fn(*args, **kwargs) and default_table has def wrapper(table="archive", *, limit=100), runs table="archive", the wrapper's own default, with the policy handed {"limit": 5}. A wrapper above scoped that takes the object under another name and hands it on (def wrapper(this, *args, **kwargs): return fn(this, *args, **kwargs)) does not change that: the stack is still read, and runs the same. Where the decorator that does not hand the object on takes it under another name (def wrapper(tenant, *args, **kwargs), or self and then fn(*args, owner=self, **kwargs) over def act(owner, table, **extra)), the kernel's walk refuses the stack (BoundArgumentKept) where the place the object would fill has a default, and since recusal 0.17.1 also where it has none and the tool takes a parameter that is not keyword-only, which 0.17.0 read (Pydantic AI then ran the call, or failed it for want of the value). The same stacks behind a functools.partial that binds by position are refused. With self the same holds: a method decorator that takes the object as self and does not hand it on (keeper, def wrapper(self, *args, **kwargs): return fn(*args, **kwargs)) is read. The kernel's advice for a wrapper that takes the object under another name, to take it under the function's name and hand it on by position, leads here where such a keeper is also on the way: @as_self @keeper def find(self, query, limit=5), as_self being the renamed wrapper written as advised, is read, judged {"query": "q", "limit": 7}, and its call raises TypeError (missing self, or ctx for a tool that takes the run context) out of run_sync. Pydantic AI hands the values in by keyword, so they do not run one place off. The reason for such a refusal says this after the kernel's advice, and to register the function itself there.
  • An output validator. A function registered with @agent.output_validator runs on the model's output, plain text and plain structured output included, and is not judged: the gate judges output functions. Behind an output function it is handed that function's result, and does not run when the function is refused.
  • A default applied somewhere else. A default an MCP server or a toolset of your own applies to a call it receives, and a decorator on an output function: for output functions the gate judges the value and does not read the function's wrappers.
  • A delegated agent. An agent called from inside a tool function runs under its own capabilities. Give every agent its own gate; is_gated(agent) reads only the agent it is given.
  • A call that fails validation. Pydantic AI answers it with a retry prompt before any execute hook runs. The tool does not run either, and the call is not on the audit log.
  • Arguments that are not plain data. JSON scalars, lists and string-keyed dicts are judged. Models, dataclasses, Enum members and other objects are refused before the policy runs. Declare a str or int and resolve application types inside the tool.

Beyond the gate. This gate judges the tool calls the framework routes through it; the paths around it inside the framework are listed above. Like every Recusal gate, it does not stop an agent that can reach a resource another way: a credential with wider rights, a shell or network path outside the agent, or a file it can write that configures the gate. Use it as one layer of several: least-privilege credentials for the agent, a sandbox or container, limits on its network egress, and an audit anchor the writer cannot reach (the limits in full).

Status

In-depth review under way. Its fixes so far are released in 0.2.2, 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 (round thirteen, beside recusal 0.16.0), stated so you can judge them. What it found that ran a value no policy judged is closed in 0.2.1 by its floor, recusal 0.17.0, whose walk refuses each shape, and each is held by a test of this package. A held wrapper whose chain of __wrapped__ comes back on itself, which beside 0.17.0 ran a parameter of its own unjudged, is closed in 0.2.2 by its floor, recusal 0.17.1. These are stated and not changed:

  • A value a functools.partial binds by position is not shown to the policy (see above), and neither is a keyword it binds that names no parameter of the function and lands in its **kwargs, when the model leaves that name out: then the application's constant runs. The model can send the same name (functools.partial(extra, mode="x") over def extra(table, limit=10, **more), and the model sends mode="evil"): its value is then judged, and it runs in place of the constant.
  • What the kernel's walk does not find, by design: an inner wrapper held where no attribute a callable names reaches it (a plain function or a lambda that names nothing as __wrapped__, a container, a slot, a wrapper built on its first use), listed in the changelog's 0.17.0 entry under "Still not found, by design"; and a chain of __wrapped__ that comes back on itself where the link back is kept on a class, in a property or a slot, or answered by __getattr__ (the 0.17.1 entry). And what a wrapper's body does, which no rule here reads (see "What the gate does not see").
  • Not covered by round thirteen: MCP toolsets, durable execution, tools the provider runs, realtime sessions, run_stream_events, any Python but 3.12, and mutation testing of the gate.

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_pydantic_ai.__all__. When a Pydantic AI release changes what the hook is handed, this package gets a release and the kernel does not.

A runnable offline demonstration, with a scripted model and no API key, is examples/pydantic_ai_gate.py and examples/pydantic_ai_audit.py.

More

One kernel, eight adapters. Each adapter package depends on recusal: recusal-crewai, recusal-google-adk, recusal-langchain, recusal-langgraph, recusal-openai, recusal-openai-agents, recusal-openai-agents-mcp and recusal-pydantic-ai. recusal-langchain also depends on recusal-langgraph, and recusal-openai-agents-mcp on recusal-openai-agents. The kernel depends on nothing.

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.

Licensed under Apache-2.0.

Metadata

Release files for recusal-pydantic-ai 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for recusal-pydantic-ai 0.2.2
File Size Uploaded Provenance Actions
recusal_pydantic_ai-0.2.2.tar.gz 70.8 kB With provenance Details for recusal_pydantic_ai-0.2.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for recusal-pydantic-ai 0.2.2
File Interpreter ABI Platform Actions
recusal_pydantic_ai-0.2.2-py3-none-any.whl Python 3 none any Details for recusal_pydantic_ai-0.2.2-py3-none-any.whl

Total release size: 125.6 kB

Release files / recusal_pydantic_ai-0.2.2.tar.gz

Download URL recusal_pydantic_ai-0.2.2.tar.gz
Size 70.8 kB
Tags Source
SHA-256 checksum
How to use checksums
48d85adcbbdb876a84f61dd5cc7bd8187f576232f5f31557fbae47b293471f6c
BLAKE2b-256 checksum
How to use checksums
34219cf87a5548b2bfa66a88d22c4c1bf48b2cef8b59891500d37a3cb21694e7
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 28, 2026.

Transparency log

Release files / recusal_pydantic_ai-0.2.2-py3-none-any.whl

Download URL recusal_pydantic_ai-0.2.2-py3-none-any.whl
Size 54.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6ef0c77410cb83c15c4e9d7b568427823b7c607f88aef8f647cdc0373b9daf52
BLAKE2b-256 checksum
How to use checksums
5a35db7676788883f51cbc516c2b656713ecd0be329a53a9bca5ee04a794c65d
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 28, 2026.

Transparency log

Security for recusal-pydantic-ai 0.2.2

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.

Select from 2 files

Attestation for recusal_pydantic_ai-0.2.2.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 28, 2026.

Transparency log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page