Opened 4 weeks ago
Last modified 14 hours ago
#66325 reopened enhancement
Abilities API: Allow abilities to declare required capabilities
| Reported by: | gziolo | Owned by: | gziolo |
|---|---|---|---|
| Priority: | normal | Milestone: | 7.2 |
| Component: | Abilities API | Version: | trunk |
| Severity: | normal | Keywords: | has-patch has-unit-tests needs-dev-note 2nd-opinion |
| Cc: | Focuses: |
Description
Today wp_get_abilities() returns every registered ability, even the ones the current user can't run. AI agents and other clients see tools they will never be allowed to use. The only way to know is to run each permission_callback, and that is not practical when listing abilities.
We looked at answering "can the current user use this ability?" through WP_Ability::check_permissions(). It doesn't fit well, because check_permissions() is bound to the input. It passes the real input to the callback, so the callback can answer questions like "can this user edit this post?". A listing mode with no input would need a new flag. Every callback would then need a third answer ("maybe"), which it can't express today. We can't use null as that signal either, because null is already valid input for abilities without an input schema.
Proposal
Let abilities declare the capabilities a user needs to run them. This builds on an idea from @ovidiu-galatan in WordPress/abilities-api#62: a simple capability-based pre-filter. Abilities the user can't access are filtered out before they are shown to AI agents, and their permission callbacks don't need to run.
<?php wp_register_ability( 'core/get-site-info', array( 'label' => __( 'Get Site Information' ), 'description' => __( 'Returns basic information about the site.' ), 'category' => 'site', 'required_capabilities' => array( 'manage_options' ), 'execute_callback' => 'wp_abilities_get_site_info', ) );
Registration
required_capabilitiesis a top-level argument, likepermission_callback. Core enforces it, so it doesn't belong inmeta, which holds hints.- It must be a list of non-empty strings.
- When
required_capabilitiesis set,permission_callbackbecomes optional. Many abilities only check one capability, so they won't need a closure anymore. - An empty list doesn't replace
permission_callback. Public abilities still need'permission_callback' => '__return_true', so "open to everyone" stays an explicit choice.
Execution
check_permissions( $input ) works in this order:
- If
required_capabilitiesis set, each capability is checked withcurrent_user_can(). If one is missing, the check fails right away. - If all capabilities pass and there is a
permission_callback, it runs with$input, as it does today. - The
wp_ability_permission_resultfilter runs on the final result, including a failure from step 1. This keeps filters like temporary permission elevation working.
So required_capabilities is the first check, and permission_callback adds rules that depend on the input.
Listing
wp_get_abilities() gets a new argument, for example 'current_user_can' => true. It leaves out abilities that declare capabilities the current user doesn't have.
- Abilities without
required_capabilitiesstay in the result. Their permission may depend on the input, so they are not hidden. - It runs with the other declarative filters (
category,namespace,meta), beforeitem_include_callback. - The REST list route (
wp-abilities/v1/abilities) gets a matching query parameter. - The REST response includes
required_capabilities, so JavaScript clients can hide UI for abilities the user can't run.
This answers "can the current user use this ability?" when listing, without calling any permission callbacks. Listing, execution, and the client all read the same list, so they can't get out of sync.
Scope
This doesn't cover every case. Abilities whose permission depends on the input will still be listed, and the final check still happens at execution. But it closes an obvious gap: today we list all abilities, even the ones the current user can't run.
Core abilities whose permission check only uses capabilities can move to required_capabilities as part of this change.
Related
- PR #13356 explores an
eligibility_callbackfor situational relevance. - WordPress/abilities-api#62
Change History (16)
This ticket was mentioned in PR #14335 on WordPress/wordpress-develop by @gziolo.
4 weeks ago
#1
- Keywords has-patch has-unit-tests added
#3
@
3 weeks ago
- Keywords needs-dev-note added
Following @jason_the_adams’s feedback on the required_capabilities proposal, I think we should clarify one point in the documentation: this list represents the minimum capabilities required for every execution, not the maximum that might be required for particular inputs.
For example, edit_posts could be declared in required_capabilities, while a permission_callback checks whether editing a particular post also requires edit_others_posts. Otherwise, discovery could hide an ability the user can use in some cases.
More formal guidance for input-dependent requirements could be a follow-up. The current implementation is a straightforward step in the right direction.
#4
@
3 weeks ago
I am developing wider enhancements for the documentation in https://github.com/WordPress/wordpress-develop/pull/14550.
This ticket was mentioned in PR #14550 on WordPress/wordpress-develop by @gziolo.
3 weeks ago
#5
This PR updates the Abilities API docblocks so they match how the code works. It changes documentation only. The code is not changed.
What changed
- Permissions. Explains how
required_capabilitiesandpermission_callbackwork together. List the capabilities needed for every execution inrequired_capabilities. Check anything that depends on the input inpermission_callback. The examples now follow this rule. - Examples. Removes
requiredfrom the input and output schemas, because it has no effect there. Adds a note that a custom category must be registered before an ability can use it. Thewp_get_abilities()sorting example now keeps the array keys. - Schemas and callbacks. Explains when an input schema is required, when the
defaultvalue is used, and what arguments the callbacks receive. Notes that exceptions thrown by callbacks are converted toWP_Error. - Execution lifecycle. Adds a short list of the hooks that
WP_Ability::execute()runs, in order. wp_get_abilities(). Clarifies which abilities reach thewp_get_abilities_item_includefilter, howmetamatching works, and whathas_required_capabilitiesdoes and does not check.- Naming. Ability names need exactly one slash. Category slugs cannot start or end with a dash.
Trac ticket: https://core.trac.wordpress.org/ticket/66325, https://core.trac.wordpress.org/ticket/65569
Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code, OpenAI Codex
Model(s): Claude Opus 5.5, GPT-6
Used for: Checking docblocks against the implementation, reviewing the PR, refining documentation, and running validation checks. I reviewed all changes.
---
This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.
🤖 Generated with Claude Code
@gziolo commented on PR #14550:
3 weeks ago
#7
Committed with https://core.trac.wordpress.org/changeset/64685.
#8
@
10 days ago
Dev Note: Required capabilities in the Abilities API in WordPress 7.2
WordPress 7.2 lets developers declare the capabilities needed to run an ability. Clients can optionally use these declarations to hide abilities when the current user lacks a required capability. This makes ability lists more relevant without running permission callbacks. An ability in the filtered list can still deny execution based on its input or other permission checks.
Registering an ability
Use the new top-level required_capabilities argument in wp_register_ability():
add_action( 'wp_abilities_api_init', static function () { wp_register_ability( 'my-plugin/get-site-title', array( 'label' => __( 'Get Site Title', 'my-plugin' ), 'description' => __( 'Returns the site title.', 'my-plugin' ), 'required_capabilities' => array( 'manage_options' ), 'execute_callback' => static function (): string { return get_option( 'blogname' ); }, 'output_schema' => array( 'type' => 'string', ), ) ); } );
required_capabilities must be a sequential list of non-empty strings. WordPress checks each capability with current_user_can(). The user must have all listed capabilities.
You can omit permission_callback when the list contains at least one capability. With an empty list, a permission callback is still required. To allow everyone to run an ability, use 'permission_callback' => '__return_true' with no required capabilities.
Use WP_Ability::get_required_capabilities() to read the declared list.
Checking permissions that depend on input
Declare the minimum capabilities needed for every execution in required_capabilities. Use permission_callback for more detailed checks that depend on the input.
For example, an ability that edits a post can use this configuration:
'required_capabilities' => array( 'edit_posts' ), 'input_schema' => array( 'type' => 'integer', 'minimum' => 1, ), 'permission_callback' => static function ( int $post_id ): bool { return current_user_can( 'edit_post', $post_id ); },
Here, edit_posts is the minimum capability required for every execution. The permission callback uses the post ID to check whether the user can edit that specific post.
During execution, WordPress checks the declared capabilities first. If a capability is missing, it skips the permission callback. Otherwise, it runs the callback when one is provided.
The wp_ability_permission_result filter can still change the result, including when a required capability is missing.
Filtering ability lists
Use has_required_capabilities to exclude abilities whose declared capabilities the current user lacks:
$abilities = wp_get_abilities( array( 'has_required_capabilities' => true, ) );
This option defaults to false. It can be combined with category, namespace, and meta filters, and runs before item_include_callback.
Abilities without declared capabilities pass this check. Other discovery filters can still exclude them.
This check does not run permission callbacks or the wp_ability_permission_result filter. Inclusion in the list does not grant permission to execute an ability. Use WP_Ability::execute() to run the ability with its permission checks.
REST API support
The abilities collection endpoint accepts the same option:
GET /wp-json/wp-abilities/v1/abilities?has_required_capabilities=true
It defaults to false and filters results before pagination.
Ability responses also include a read-only required_capabilities array in the view and edit contexts. The array is empty when no capabilities are declared.
Existing REST access and exposure rules still apply. Settings such as meta.public do not grant permission to execute an ability.
Updating existing abilities
Existing permission callbacks continue to work. You can move capability checks into required_capabilities when they apply to every execution. Keep input-dependent checks in the callback.
If your plugin supports WordPress versions before 7.2, keep a compatible permission callback. Those versions do not enforce required_capabilities.
Core now uses required_capabilities with manage_options for core/get-site-info, core/get-environment-info, and core/settings-get.
#9
@
7 days ago
- Keywords 2nd-opinion added
- Resolution fixed
- Status closed → reopened
@gziolo @jason_the_adams -
I'm concerned about the changes in this ticket, and think it should be reverted from 7.2 and instead considered as a potential candidate for 7.3.
Not just because it's a public API change that seems to have been merged quickly and without much discussion (https://github.com/WordPress/wordpress-develop/pull/14335 seems to have been merged to core-develop without any code review), but also because it seems to ignore feedback (cc @swissspidy ) or alternatives.
Regarding the implementation itself, IMO it's not self-documenting, and is even outright confusing. Why do we need two properties required_permissions and permission_callback at all, why does one only apply to listing abilities and one when executing permissions, and which one, why do I need to define it twice etc? etc etc.
Regarding the issue it's attempting to address, in WP7.1 we already added `meta.public` explicitly and intentionally as the way to determine what Abilities should be exposed when using wp_get_abilities(), and downstream wrappers like WP_REST and MCP. It would be trivial to change meta.public to take a bool|callable():bool so developers can define whether an ability should be "publicly" viewable in various contexts e.g. if current_user_can( $do_something );
Another alternative approach that doesn't grow our public API footprint is to simply stabilize and reuse WP_Ability::check_permissions(). It _already_ has a nullable $input, so we can update the docs to make it explicit that you need to accomodate for it also being applied when listing abilities, e.g. current_user_can( $do_something, $input['post_id'] ?? null ).
---
There are likely other viable alternatives here if other contributors are given an opportunity to weigh in.
(I'm not seeing a way to tag this as 7.2, if someone with those perms can do so so this is considered before RC1, please do so 🙇)
#10
@
7 days ago
Thanks for your input, @justlevine! Rather than push this to 7.3, I'd rather see if we can agree on this or arrive at an alternative. If we still don't like the result, we can revert before the end date. I think it's important that we provide a way to reduce tool lists to reduce tokens and failed tool calls.
You're raising some fair alternatives to consider. This does introduce the risk of having this list get out of sync with the capability checks in the permissions callback.
I like using WP_Ability::check_permissions over making meta.public a callback, as the former is more closely tied to what we're examining here. I wonder what would happen if we suddenly started using the permission callback without input with existing Abilities to narrow the list. Would some get removed by accident, or possibly throw an error? I'm not sure how folks are handling input being null right now. Still, the fact that $input is nullable does lend itself in this direction already.
What do you think, @gziolo?
#11
@
7 days ago
Thanks both. The goal is to avoid listing abilities when we already know the user lacks the capabilities needed to execute them. This is a common pain point for clients, and capability filtering has been discussed for over a year, including the earlier feedback and the alternative in https://github.com/WordPress/wordpress-develop/pull/13356.
Clients list abilities before they have input for execution. Existing permission callbacks can have typed parameters, such as an integer post ID. Passing null can cause a type error, so using these callbacks during discovery introduces a backward compatibility concern. Even callbacks that accept null may have different idea how to handle null and accidentally reject it.
Making meta.public callable also raises compatibility concerns. REST and the MCP Adapter currently use it as a boolean, together with their own exposure overrides. Changing that contract would require coordinated changes in consumers and would still leave execution permissions separate.
required_capabilities provides a best effort filter using prerequisites that apply to every execution. Abilities without a declaration remain listed. Core checks the declared capabilities again during execution, then runs permission_callback for additional checks that depend on input.
This addresses the duplication concern by enforcing the declaration in both places. The callback does not need to repeat those checks, and capability-only abilities can omit it. I think this limited approach is worth keeping. Being listed never replaces the final permission check.
I am open to dropping this approach if we identify risks that outweigh the benefit of providing an option to filter out abilities the user cannot execute.
#12
@
7 days ago
Rather than push this to 7.3, I'd rather see if we can agree on this or arrive at an alternative.
Thanks @jason_the_adams for the suggestion, I didn't realize this could be a possibility so late in the release cycle. Happy to try 💙
Existing permission callbacks can have typed parameters, such as an integer post ID. Passing null can cause a type error, so using these callbacks during discovery introduces a backward compatibility concern. Even callbacks that accept null may have different idea how to handle null and accidentally reject it.
Thanks for raising this point, @gziolo . Can you clarify what you feel the blast radius for this might be?
My understanding is that if someone used typed parameters that don't adhere to the existing documented shape (WP_Ability documents the callback as receiving "optional mixed input", and check_permissions() explicitly accepts null), they would get a non-fatal WP_Error, leaving the ability executable but not listed. Similarly if they called an untyped $input['post_id']. And FWIW, this only affects abilities that have an input schema which doesn't accept a top-level null and also doesn't declare a default.
While a longer feedback cycle would verify the breadth of the impact, bugfixes (e.g. "fix: enforce permission checks in wp_get_abilities()") that have side effects for problematic downstream code are not uncommon, especially when they're aligning with documented behavior.
(If the remaining potential false negatives are still a concern, we could treat a callback that throws on null as inconclusive and keep it listed during discovery. Not saying that's ideal, just that we have options short of a new public API. Fixing the central lifecycle issue with Ability registration so they're lazy-loaded would open up even more options, here and for other tickets, but my guess is that's too big to do when Core is already this late into beta.)
Making meta.public callable also raises compatibility concerns. REST and the MCP Adapter currently use it as a boolean, together with their own exposure overrides. Changing that contract would require coordinated changes in consumers and would still leave execution permissions separate.
Not sure I follow. I'm picturing WP_Ability as responsible for resolving the callable internally, so external consumers are still only always dealing with a bool value, and don't need to change anything...
#13
@
7 days ago
@justlevine fair point on the process. I'm not neutral here: the idea came from my comment in https://github.com/WordPress/abilities-api/issues/62, and I got props on [64500].
On the design, I think required capabilities and permission checks are two different things. required_capabilities is a plain list of capabilities. It needs no input, so it works when a client lists abilities. permission_callback can check many things, and it may need the input, for example a post ID. When a client lists abilities, there is no input yet.
That is the problem with running the permission check at listing time. Callbacks that need the input deny everyone. For example, ai/get-post-terms in the AI plugin uses Posts::permission_callback( array $args ). With no input it throws a TypeError, and the ability disappears from the list even for administrators.
So I think keeping both is right. The list filters what we can know without input, and permission_callback decides the rest at execution.
#14
@
6 days ago
Hey @ovidiu-galatan noted and I appreciate your perspective🙇
On the design, I think required capabilities and permission checks are two different things. required_capabilities is a plain list of capabilities. It needs no input, so it works when a client lists abilities. permission_callback can check many things, and it may need the input, for example a post ID. When a client lists abilities, there is no input yet.
If I understand, (cc @jason_the_adams since you said something similar in DM), this perspective holds true from the Core implementation details side of things, and not the consumption. We (core developers) need a way to hide Abilities that a user doesn't have "permission" to run, but because we don't have a way to determine whether to current_user_can() without the ability input, we ostensibly need to decouple the "required capability" from the "permission callback" that checks if it applies to the user.
I'm proposing we look at this from the holistic perspective of those consuming the public API (instead of us building it). In that model, we have two separate needs:
- Can the current user run this ability, generally or with this input? (
::execute(), viapermission_callback) - Should this ability be visible, generally or in the current context? (
wp_get_abilities(), viameta.public)
Lacking the "required capabilities" is one reason to hide an ability, but not the only one, and sometimes you want to show it even if they don't have them. MCP is a good example: you often want your agent to know the site can my/custom-cpt/update, so it can prompt you to log in with elevated perms, instead of assuming the functionality doesn't exist and falling back to core/posts/update or working around it with REST/CLI.
Now to shift back to the Core implementation details:
- The current lifecycle encapsulation issues mean we can't just do a
current_user_can()check beforewp_register_ability()and pass the result tometa.public: bool. - Developers ignoring the docs and types on
check_permissions()andpermission_callbackmight not be handling anullvalue, which means reusingcheck_permissions()internally may cause some downstream errors without additional changes to mitigate.
Solving for either of these issues doesn't require us to invent a declared capability list that coexists with, and partially duplicates, a permission callback. That pattern doesn't exist anywhere else in WordPress (despite this not being a unique need). It's also much less self-documenting, leaving the developer to figure out which check goes where.
And if you decouple them back into something like required_permissions_to_view or view_permission_callback then we've reinvented meta.public from first principles.
(Another alternative per this holistic exploration is to deprecate the existing permission_callback entirely in favor of a new callback whose contract explicitly requires handling a null input, since it would also be called from wp_get_abilities(). This would allow for opt-in adoption just like required_capabilities, without forcing developers to define their capability checks multiple times. Personally I still think this is subpar to just using meta.public per its semantic meaning and avoiding tying the ability to view to the ability to execute, but IMO it's still better than required_capabilities, and mitigates the potential for breaking changes. )
For example, ai/get-post-terms in the AI plugin uses Posts::permission_callback( array $args ). With no input it throws a TypeError, and the ability disappears from the list even for administrators.
It's definitely concerning that even we aren't handling this correctly. I already thought reusing permission_callback was a worse fit than meta.public, and knowing the blast radius is bigger (even though IRL we can probably turn that TypeError into a _deprecated_argument(), I like that option even less. But to me it's an argument against reusing the callback, not for coupling visibility to capabilities at the API level, nor that having a required_capabilities alongside permission_callback and public is the proper way to do it. Is there a case required_capabilities covers that a callable meta.public wouldn't? If so, please share.
Hoping you see and agree with this perspective shift, even if it takes you to a different ideal solution. Please lmk what you think and we can go from there 🙇
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
What
Abilities can now declare the capabilities a user needs to run them:
Today
wp_get_abilities()lists every ability, even the ones the current user can't run. With this change, callers like AI agents and MCP adapters can ask for only the abilities the current user can use. No permission callbacks need to run for that.How it works
Registration
required_capabilitiesis a top-level argument, likepermission_callback. It must be a list of non-empty strings.permission_callbackbecomes optional.permission_callback. Public abilities still need'permission_callback' => '__return_true'.permission_callbackthat is set must be callable, even when capabilities are listed.Execution
check_permissions( $input )combines both checks with AND:current_user_can(). If one is missing, the check fails and the callback doesn't run.permission_callback, it runs with$input, as it does today.wp_ability_permission_resultfilter runs on the final result, including a failure from step 1.If only one of the two is set, that one decides. Custom
ability_classsubclasses skip the registration checks, socheck_permissions()also returns an error when the callback is not callable (ability_invalid_permission_callback) or when both are missing (ability_missing_permission_callback).Listing
wp_get_abilities()accepts'current_user_can' => true. It leaves out abilities that declare capabilities the current user doesn't have.required_capabilitiesstay in the result, because their permission may depend on the input.category,namespace, andmetafilters and beforeitem_include_callback.wp-abilities/v1/abilitiesroute accepts a matchingcurrent_user_canquery parameter.required_capabilities, so JavaScript clients can hide UI for abilities the user can't run.Core abilities
core/get-site-info,core/get-environment-info, andcore/settings-getonly checkedmanage_options. They now userequired_capabilitiesinstead of a closure.New public API
required_capabilitiesregistration argument.WP_Ability::get_required_capabilities(): array.current_user_canargument forwp_get_abilities()and the REST list route.required_capabilitiesfield in the REST response.Testing
Follow-ups
@wordpress/abilitiesand@wordpress/core-abilities) live in the Gutenberg repository and will follow separately.Use of AI Tools
AI assistance: Yes
Tool(s): Claude Code
Model(s): Claude Opus 5.5
Used for: Implementation and tests, based on the design in the Trac ticket. I reviewed and adjusted the code and tests.
---
This Pull Request is for code review only. Please keep all other discussion in the Trac ticket. Do not merge this Pull Request. See GitHub Pull Requests for Code Review in the Core Handbook for more details.
🤖 Generated with Claude Code