Adding your own tools¶
Alpha
The event and class names below are the ones in the current code. They may still change before the first stable release; any change will be listed in the Release Notes.
Adding tools from another extension¶
This extension keeps a registry of tools, the operations an AI client may call. Your own
extension can add tools by listening to the civi.mcp.tools event
(Civi\Mcp\Tools\CollectToolsEvent) and registering them. Register the listener from
hook_civicrm_config, or from a class that extends Civi\Core\Service\AutoSubscriber (picked up by
the scan-classes mixin), which is the usual way:
use Civi\Mcp\Tools\Ability;
use Civi\Mcp\Tools\CollectToolsEvent;
\Civi::dispatcher()->addListener(CollectToolsEvent::NAME, function (CollectToolsEvent $event) {
$event->add(new Ability(
name: 'myext_open_grants',
title: 'Open grants',
description: 'Lists open grant applications.',
inputSchema: ['type' => 'object', 'properties' => new \stdClass(), 'additionalProperties' => FALSE],
readOnly: TRUE,
permission: 'access CiviGrant',
callback: fn(array $args, $context) => [/* APIv4 results, checkPermissions on */],
));
});
Rules every tool must follow:
- Read-only. Tools not marked
readOnly: TRUEare dropped. - Declare a permission. Every tool names at least one CiviCRM permission the user needs, on top of the extension's own connect an AI client permission. Users without it are not offered the tool.
- Permission checks on. Read through APIv4 or SearchKit with
checkPermissionson. Never use direct SQL. - Bounded. Respect the site's row cap.
This is how site-specific tools should be built. See Scope.
Narrowing a core tool¶
The core tools civi_describe and civi_get are offered to every connected user, under that
user's own permissions. To offer one only to some users, restrict it from your extension, after
the core has registered it (a lower priority runs later):
public static function getSubscribedEvents(): array {
return [CollectToolsEvent::NAME => ['restrictCoreTools', -100]];
}
public function restrictCoreTools(CollectToolsEvent $event): void {
// Adds one requirement on top of the tool's own. A string is one permission; a list means
// "any one of these".
$event->restrict('civi_get', ['view all contacts', 'edit all contacts', 'administer CiviCRM']);
}
Never edit another extension's tool to narrow it; restrict it instead.
Showing more than a user's own permissions¶
A tool never shows anyone more than CiviCRM itself would, with one exception: a SearchKit display set to bypass ACLs. Its rules are on their own page, Publishing a SearchKit display.