merge: tool groups with inherited mode and 'nur lesen' per group

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-26 16:32:39 +02:00
co-authored by Claude Opus 5.5
10 changed files with 847 additions and 92 deletions
+192 -14
View File
@@ -7,6 +7,12 @@ namespace LIT\MCP\Abilities;
/**
* Decides per ability whether it is a direct MCP tool, only reachable through the
* adapter's meta-tools, or disabled (spec §4.3). Ability::isDirect() is the default.
*
* Abilities are grouped by the integration they come from. Resolution: tool override ›
* group override › tool default. A group's "nur lesen" switch disables every ability of the
* group that is not annotated readonly, whatever the modes say. REQUIRED abilities always
* keep their default. Group entries live in the same option under keys that start with "@"
* (ability names always contain "/", so they cannot collide).
*/
final class ExposurePolicy
{
@@ -16,6 +22,12 @@ final class ExposurePolicy
public const DISABLED = 'disabled';
public const MODES = [self::DIRECT, self::INDIRECT, self::DISABLED];
/** Option key prefix of a group's mode: "@group:<integration id>" => mode. */
public const GROUP_PREFIX = '@group:';
/** Option key prefix of a group's read-only switch: "@readonly:<integration id>" => true. */
public const READONLY_PREFIX = '@readonly:';
/**
* Image/embedded-resource results only work for direct tools (ruling Q6 / task 6
* dispatch): lit/media-preview (ImageContent) and lit/media-download (embedded
@@ -26,9 +38,41 @@ final class ExposurePolicy
/** Entry point for every conversation – must always stay a direct tool. */
public const REQUIRED = ['lit/guide'];
/** @param array<string, string> $overrides Ability name => mode. */
public function __construct(private array $overrides = [])
/** @var array<string, string> Ability name => mode. */
private array $tools = [];
/** @var array<string, string> Group id => mode. */
private array $groupModes = [];
/** @var array<string, true> Group ids switched to "nur lesen". */
private array $readonlyGroups = [];
/** @var array<string, string>|null Ability name => group id; null until resolved. */
private ?array $groups = [];
/** @var (callable(): array<string, string>)|null Lazy source of $groups. */
private $groupSource = null;
/**
* @param array<string, string|bool> $overrides Option content: ability name => mode, plus
* "@group:<id>" => mode and "@readonly:<id>" => true.
*/
public function __construct(array $overrides = [])
{
foreach ($overrides as $key => $value) {
$key = (string) $key;
if (str_starts_with($key, self::GROUP_PREFIX)) {
if (is_string($value) && in_array($value, self::MODES, true)) {
$this->groupModes[substr($key, strlen(self::GROUP_PREFIX))] = $value;
}
} elseif (str_starts_with($key, self::READONLY_PREFIX)) {
if ($value === true) {
$this->readonlyGroups[substr($key, strlen(self::READONLY_PREFIX))] = true;
}
} elseif (is_string($value)) {
$this->tools[$key] = $value;
}
}
}
public static function fromOption(): self
@@ -36,11 +80,98 @@ final class ExposurePolicy
return new self(self::sanitize(get_option(self::OPTION, [])));
}
/**
* Copy of this policy that knows which group (integration id) each ability belongs to.
* Without it, group entries have no effect. A callable is resolved on first use – boot runs
* on plugins_loaded, before the theme (Divi) is loaded, so the map must not be built there.
*
* @param array<string, string>|(callable(): array<string, string>) $groups Ability name => group id.
*/
public function withGroups(array|callable $groups): self
{
$clone = clone $this;
if (is_array($groups)) {
$clone->groups = $groups;
$clone->groupSource = null;
} else {
$clone->groups = null;
$clone->groupSource = $groups;
}
return $clone;
}
public function mode(Ability $ability): string
{
$mode = $this->overrides[$ability->name()] ?? null;
if (in_array($ability->name(), self::REQUIRED, true)) {
return $this->defaultMode($ability);
}
return is_string($mode) && self::isAllowed($ability->name(), $mode) ? $mode : $this->defaultMode($ability);
if ($this->disabledByReadonly($ability)) {
return self::DISABLED;
}
return $this->toolOverride($ability->name()) ?? $this->inheritedMode($ability);
}
/** Mode the ability gets without an override of its own: group override › tool default. */
public function inheritedMode(Ability $ability): string
{
$name = $ability->name();
$groupMode = $this->groupModeOf($name);
if ($groupMode === null || in_array($name, self::REQUIRED, true)) {
return $this->defaultMode($ability);
}
return self::isAllowed($name, $groupMode) ? $groupMode : self::DIRECT;
}
/** True if the group's mode is not allowed for this ability and it falls back to "direct". */
public function groupModeAdjusted(Ability $ability): bool
{
$name = $ability->name();
$groupMode = $this->groupModeOf($name);
return $groupMode !== null
&& ! in_array($name, self::REQUIRED, true)
&& ! self::isAllowed($name, $groupMode);
}
/** True if the group's "nur lesen" switch disables this (writing) ability. */
public function disabledByReadonly(Ability $ability): bool
{
$group = $this->groupOf($ability->name());
if ($group === null || ! isset($this->readonlyGroups[$group])) {
return false;
}
if (in_array($ability->name(), self::REQUIRED, true)) {
return false;
}
return ($ability->annotations()['readonly'] ?? false) !== true;
}
public function hasToolOverride(string $name): bool
{
return $this->toolOverride($name) !== null;
}
public function toolOverride(string $name): ?string
{
$mode = $this->tools[$name] ?? null;
return $mode !== null && self::isAllowed($name, $mode) ? $mode : null;
}
public function groupMode(string $group): ?string
{
return $this->groupModes[$group] ?? null;
}
public function isReadonly(string $group): bool
{
return isset($this->readonlyGroups[$group]);
}
public function defaultMode(Ability $ability): string
@@ -94,29 +225,76 @@ final class ExposurePolicy
}
/**
* Settings API sanitize callback for the option.
* Settings API sanitize callback for the option. Keeps valid ability entries (name => allowed
* mode), "@group:<id>" => mode and "@readonly:<id>" => true; drops everything else. With
* $groupIds, only those group ids are accepted.
*
* @return array<string, string>
* @param list<string>|null $groupIds Known group (integration) ids; null = any well-formed id.
* @return array<string, string|true>
*/
public static function sanitize(mixed $input): array
public static function sanitize(mixed $input, ?array $groupIds = null): array
{
if (! is_array($input)) {
return [];
}
$clean = [];
foreach ($input as $name => $mode) {
if (
is_string($name)
&& is_string($mode)
&& preg_match('#^[a-z0-9-]+/[a-z0-9-]+$#', $name) === 1
&& self::isAllowed($name, $mode)
foreach ($input as $key => $value) {
if (! is_string($key)) {
continue;
}
if (str_starts_with($key, self::GROUP_PREFIX)) {
if (
self::isGroupId(substr($key, strlen(self::GROUP_PREFIX)), $groupIds)
&& is_string($value)
&& in_array($value, self::MODES, true)
) {
$clean[$key] = $value;
}
} elseif (str_starts_with($key, self::READONLY_PREFIX)) {
if (
self::isGroupId(substr($key, strlen(self::READONLY_PREFIX)), $groupIds)
&& ($value === true || $value === '1' || $value === 1)
) {
$clean[$key] = true;
}
} elseif (
is_string($value)
&& preg_match('#^[a-z0-9-]+/[a-z0-9-]+$#', $key) === 1
&& self::isAllowed($key, $value)
) {
$clean[$name] = $mode;
$clean[$key] = $value;
}
}
ksort($clean);
return $clean;
}
/** @param list<string>|null $groupIds */
private static function isGroupId(string $id, ?array $groupIds): bool
{
if (preg_match('#^[a-z0-9-]+$#', $id) !== 1) {
return false;
}
return $groupIds === null || in_array($id, $groupIds, true);
}
private function groupOf(string $name): ?string
{
if ($this->groups === null) {
$this->groups = $this->groupSource !== null ? ($this->groupSource)() : [];
}
return $this->groups[$name] ?? null;
}
private function groupModeOf(string $name): ?string
{
$group = $this->groupOf($name);
return $group === null ? null : ($this->groupModes[$group] ?? null);
}
}
+176 -41
View File
@@ -4,18 +4,24 @@ declare(strict_types=1);
namespace LIT\MCP\Admin;
use LIT\MCP\Abilities\Ability;
use LIT\MCP\Abilities\ExposurePolicy;
use LIT\MCP\Integrations\IntegrationRegistry;
/**
* Tab "Tools": direct/indirect/disabled exposure per ability (spec §8.4). Only the modes
* ExposurePolicy::isAllowed() allows for a given ability are offered; "Standard" saves nothing,
* so a later version's changed default takes effect automatically.
* Tab "Tools": direct/indirect/disabled exposure per ability (spec §8.4), grouped by the
* integration the ability comes from. Each group has its own mode (inherited by its tools)
* and a "nur lesen" switch. Only the modes ExposurePolicy::isAllowed() allows for a given
* ability are offered; "Standard"/"wie Gruppe" saves nothing, so a later version's changed
* default takes effect automatically.
*/
final class ToolsTab implements AdminTab
{
public const GROUP = 'lit_mcp_tools';
/** More direct tools than this cost noticeable context in every claude.ai conversation. */
public const DIRECT_WARNING_THRESHOLD = 25;
public function __construct(private IntegrationRegistry $registry, private ExposurePolicy $policy)
{
}
@@ -34,11 +40,21 @@ final class ToolsTab implements AdminTab
{
register_setting(self::GROUP, ExposurePolicy::OPTION, [
'type' => 'array',
'sanitize_callback' => [ExposurePolicy::class, 'sanitize'],
'sanitize_callback' => [$this, 'sanitize'],
'default' => [],
]);
}
/**
* Sanitize callback: ExposurePolicy::sanitize() restricted to the known group ids.
*
* @return array<string, string|true>
*/
public function sanitize(mixed $input): array
{
return ExposurePolicy::sanitize($input, $this->registry->ids());
}
public function registerActions(): void
{
}
@@ -64,50 +80,169 @@ final class ToolsTab implements AdminTab
'Das Divi-Code-Modul ist immer erlaubt (nur nachrangig) und hat keine eigene Einstellung.',
'wp-lit-mcp'
) . '</p>';
$policy = $this->policy->withGroups($this->registry->groupMap());
$this->renderCounter(count($policy->directNames($this->registry->abilities())));
echo '<form method="post" action="options.php">';
settings_fields(self::GROUP);
echo '<table class="widefat striped"><thead><tr><th>' . esc_html__('Tool', 'wp-lit-mcp') . '</th><th>'
. esc_html__('Einstellung', 'wp-lit-mcp') . '</th></tr></thead><tbody>';
foreach ($this->registry->abilities() as $ability) {
$name = $ability->name();
$current = $this->policy->mode($ability);
$isDefault = $current === $this->policy->defaultMode($ability);
printf(
'<tr><td><strong>%s</strong><br><code>%s</code></td><td><select name="%s[%s]">',
esc_html($ability->label()),
esc_html($name),
esc_attr(ExposurePolicy::OPTION),
esc_attr($name)
);
printf(
'<option value=""%s>%s</option>',
selected($isDefault, true, false),
esc_html(sprintf(
/* translators: %s: default mode */
__('Standard (%s)', 'wp-lit-mcp'),
$this->modeLabel($this->policy->defaultMode($ability))
))
);
foreach (ExposurePolicy::MODES as $mode) {
if (! ExposurePolicy::isAllowed($name, $mode)) {
continue;
}
printf(
'<option value="%s"%s>%s</option>',
esc_attr($mode),
selected(! $isDefault && $current === $mode, true, false),
esc_html($this->modeLabel($mode))
);
}
echo '</select></td></tr>';
foreach ($this->registry->grouped() as $group => $abilities) {
$this->renderGroup($policy, $group, $abilities);
}
echo '</tbody></table>';
submit_button();
echo '</form>';
}
private function renderCounter(int $direct): void
{
echo '<p><strong>' . esc_html(sprintf(
/* translators: %d: number of direct tools */
_n('Direkt sichtbar: %d Tool', 'Direkt sichtbar: %d Tools', $direct, 'wp-lit-mcp'),
$direct
)) . '</strong></p>';
if ($direct > self::DIRECT_WARNING_THRESHOLD) {
echo '<p class="description"><strong>' . esc_html__('Achtung:', 'wp-lit-mcp') . '</strong> '
. esc_html__(
'Viele direkte Tools kosten in claude.ai in jeder Unterhaltung Kontext.',
'wp-lit-mcp'
) . ' '
. esc_html__('Selten gebrauchte Tools besser auf „indirekt“ stellen.', 'wp-lit-mcp')
. '</p>';
}
}
/** @param list<Ability> $abilities */
private function renderGroup(ExposurePolicy $policy, string $group, array $abilities): void
{
$count = count($abilities);
$mixed = false;
foreach ($abilities as $ability) {
$mixed = $mixed || $policy->hasToolOverride($ability->name());
}
printf(
'<details open class="lit-mcp-tool-group"><summary>%s</summary>',
esc_html(sprintf(
/* translators: 1: group label, 2: number of tools */
_n('%1$s (%2$d Tool)', '%1$s (%2$d Tools)', $count, 'wp-lit-mcp'),
$this->groupLabel($group),
$count
))
);
$groupMode = $policy->groupMode($group);
printf(
'<p><label>%s <select name="%s[%s]">',
esc_html__('Ganze Gruppe:', 'wp-lit-mcp'),
esc_attr(ExposurePolicy::OPTION),
esc_attr(ExposurePolicy::GROUP_PREFIX . $group)
);
printf(
'<option value=""%s>%s</option>',
selected($groupMode === null, true, false),
esc_html__('Standard der Tools', 'wp-lit-mcp')
);
foreach (ExposurePolicy::MODES as $mode) {
printf(
'<option value="%s"%s>%s</option>',
esc_attr($mode),
selected($groupMode === $mode, true, false),
esc_html($this->modeLabel($mode))
);
}
echo '</select></label> ';
printf(
'<label><input type="checkbox" name="%s[%s]" value="1"%s> %s</label>',
esc_attr(ExposurePolicy::OPTION),
esc_attr(ExposurePolicy::READONLY_PREFIX . $group),
checked($policy->isReadonly($group), true, false),
esc_html__('nur lesen (schreibende Tools dieser Gruppe aus)', 'wp-lit-mcp')
);
if ($mixed) {
echo ' <em>' . esc_html__('gemischt – einzelne Tools haben eigene Einstellungen', 'wp-lit-mcp') . '</em>';
}
echo '</p>';
echo '<table class="widefat striped"><thead><tr><th>' . esc_html__('Tool', 'wp-lit-mcp') . '</th><th>'
. esc_html__('Einstellung', 'wp-lit-mcp') . '</th></tr></thead><tbody>';
foreach ($abilities as $ability) {
$this->renderTool($policy, $ability, $groupMode !== null);
}
echo '</tbody></table></details>';
}
private function renderTool(ExposurePolicy $policy, Ability $ability, bool $groupOverride): void
{
$name = $ability->name();
$own = $policy->toolOverride($name);
$locked = $policy->disabledByReadonly($ability);
$required = in_array($name, ExposurePolicy::REQUIRED, true);
printf(
'<tr><td><strong>%s</strong><br><code>%s</code></td><td><select name="%s[%s]"%s>',
esc_html($ability->label()),
esc_html($name),
esc_attr(ExposurePolicy::OPTION),
esc_attr($name),
$locked ? ' disabled' : ''
);
$inherited = $this->modeLabel($policy->inheritedMode($ability));
printf(
'<option value=""%s>%s</option>',
selected($own === null, true, false),
esc_html($groupOverride && ! $required
/* translators: %s: mode inherited from the group */
? sprintf(__('wie Gruppe (%s)', 'wp-lit-mcp'), $inherited)
/* translators: %s: default mode */
: sprintf(__('Standard (%s)', 'wp-lit-mcp'), $this->modeLabel($policy->defaultMode($ability))))
);
foreach (ExposurePolicy::MODES as $mode) {
if (! ExposurePolicy::isAllowed($name, $mode)) {
continue;
}
printf(
'<option value="%s"%s>%s</option>',
esc_attr($mode),
selected($own === $mode, true, false),
esc_html($this->modeLabel($mode))
);
}
echo '</select>';
if ($locked && $own !== null) {
// A disabled select is not submitted – keep the tool's own setting for later.
printf(
'<input type="hidden" name="%s[%s]" value="%s">',
esc_attr(ExposurePolicy::OPTION),
esc_attr($name),
esc_attr($own)
);
}
$note = match (true) {
$locked => __('durch ‚nur lesen‘ aus', 'wp-lit-mcp'),
$own === null && $policy->groupModeAdjusted($ability)
=> __('„indirekt“ geht hier nicht – bleibt direkt', 'wp-lit-mcp'),
default => '',
};
if ($note !== '') {
echo ' <em>' . esc_html($note) . '</em>';
}
echo '</td></tr>';
}
private function groupLabel(string $group): string
{
return match ($group) {
'core' => __('Grundlagen', 'wp-lit-mcp'),
'wordpress' => __('WordPress', 'wp-lit-mcp'),
'media' => __('Medien', 'wp-lit-mcp'),
'pods' => __('Pods', 'wp-lit-mcp'),
'divi' => __('Divi', 'wp-lit-mcp'),
default => $group,
};
}
private function modeLabel(string $mode): string
{
return match ($mode) {
+56 -10
View File
@@ -11,8 +11,8 @@ final class IntegrationRegistry
/** @var list<Integration> */
private array $integrations;
/** @var list<Ability>|null */
private ?array $abilities = null;
/** @var list<array{Integration, list<Ability>}>|null Available integrations with their abilities. */
private ?array $loaded = null;
public function __construct(Integration ...$integrations)
{
@@ -31,15 +31,61 @@ final class IntegrationRegistry
/** @return list<Ability> */
public function abilities(): array
{
if ($this->abilities === null) {
$abilities = [];
foreach ($this->available() as $integration) {
array_push($abilities, ...$integration->abilities());
}
$this->abilities = $abilities;
$abilities = [];
foreach ($this->loaded() as [, $own]) {
array_push($abilities, ...$own);
}
return $this->abilities;
return $abilities;
}
/**
* Abilities of the available integrations, grouped by integration id (registry order).
*
* @return array<string, list<Ability>>
*/
public function grouped(): array
{
$groups = [];
foreach ($this->loaded() as [$integration, $own]) {
$groups[$integration->id()] = array_merge($groups[$integration->id()] ?? [], $own);
}
return $groups;
}
/** @return array<string, string> Ability name => integration id (the ability's group). */
public function groupMap(): array
{
$map = [];
foreach ($this->grouped() as $id => $abilities) {
foreach ($abilities as $ability) {
$map[$ability->name()] = $id;
}
}
return $map;
}
/** @return list<string> Ids of all known integrations, available or not. */
public function ids(): array
{
return array_values(array_unique(array_map(
static fn (Integration $integration): string => $integration->id(),
$this->integrations
)));
}
/** @return list<array{Integration, list<Ability>}> */
private function loaded(): array
{
if ($this->loaded === null) {
$this->loaded = array_map(
static fn (Integration $integration): array => [$integration, $integration->abilities()],
$this->available()
);
}
return $this->loaded;
}
}
+1 -1
View File
@@ -73,7 +73,7 @@ final class Plugin
new DiviIntegration($schema, $changeLog)
);
$policy = ExposurePolicy::fromOption();
$policy = ExposurePolicy::fromOption()->withGroups($registry->groupMap(...));
(new AbilityRegistrar($registry, $policy))->register();
(new ServerRegistrar(
$registry,