feat: whitelisted WordPress settings tools
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Settings;
|
||||
|
||||
use WP_Post;
|
||||
|
||||
/**
|
||||
* The WordPress options LIT MCP may read and write (spec §6.5), with validation.
|
||||
*
|
||||
* validate() arms are delegated to one-purpose helper methods rather than inline
|
||||
* ternaries: PHPCompatibility's RemovedTernaryAssociativity sniff misreads a `match`
|
||||
* whose arms are themselves ternaries as chained ternaries and rejects them, even
|
||||
* though PHP itself parses them fine (controller ruling P3).
|
||||
*/
|
||||
final class SettingsWhitelist
|
||||
{
|
||||
/** key => [group, type, description] */
|
||||
public const SETTINGS = [
|
||||
'blogname' => ['general', 'string', 'Titel der Website'],
|
||||
'blogdescription' => ['general', 'string', 'Untertitel der Website'],
|
||||
'WPLANG' => ['general', 'string', 'Sprache (Locale, z. B. de_DE; en_US = Englisch); nur installierte Sprachen'],
|
||||
'timezone_string' => ['general', 'string', 'Zeitzone, z. B. Europe/Berlin'],
|
||||
'date_format' => ['general', 'string', 'Datumsformat (PHP), z. B. j. F Y'],
|
||||
'time_format' => ['general', 'string', 'Zeitformat (PHP), z. B. H:i'],
|
||||
'show_on_front' => ['reading', 'string', 'Startseite: posts (neueste Beiträge) oder page (statische Seite)'],
|
||||
'page_on_front' => ['reading', 'integer', 'ID der statischen Startseite (0 = keine)'],
|
||||
'page_for_posts' => ['reading', 'integer', 'ID der Beitragsseite (0 = keine)'],
|
||||
'posts_per_page' => ['reading', 'integer', 'Beiträge pro Seite (1–100)'],
|
||||
'default_comment_status' => ['discussion', 'string', 'Kommentare für neue Beiträge: open oder closed'],
|
||||
'default_ping_status' => ['discussion', 'string', 'Pingbacks für neue Beiträge: open oder closed'],
|
||||
'permalink_structure' => ['permalinks', 'string', 'Permalink-Struktur, z. B. /%postname%/ (leer = einfach)'],
|
||||
'site_icon' => ['site_icon', 'integer', 'Anhang-ID des Website-Icons (Bild, empfohlen 512×512; 0 = keins)'],
|
||||
];
|
||||
|
||||
public const BLOCKED = ['admin_email', 'users_can_register', 'default_role', 'siteurl', 'home'];
|
||||
public const GROUPS = ['general', 'reading', 'discussion', 'permalinks', 'site_icon'];
|
||||
|
||||
private const INTEGER_KEYS = ['page_on_front', 'page_for_posts', 'posts_per_page', 'site_icon'];
|
||||
|
||||
public function current(string $key): mixed
|
||||
{
|
||||
$value = get_option($key);
|
||||
if ($key === 'WPLANG') {
|
||||
return $value === '' || $value === false ? 'en_US' : (string) $value;
|
||||
}
|
||||
|
||||
if (in_array($key, self::INTEGER_KEYS, true)) {
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
return (string) $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $pending All values of the current call.
|
||||
* @return string|null Error message, null when valid.
|
||||
*/
|
||||
public function validate(string $key, mixed $value, array $pending): ?string
|
||||
{
|
||||
if (in_array($key, self::BLOCKED, true)) {
|
||||
return 'Gesperrt: aus Sicherheitsgründen nicht über LIT MCP änderbar.';
|
||||
}
|
||||
|
||||
if (! isset(self::SETTINGS[$key])) {
|
||||
return 'Nicht freigegeben; erlaubt: ' . implode(', ', array_keys(self::SETTINGS)) . '.';
|
||||
}
|
||||
|
||||
return match ($key) {
|
||||
'blogname', 'blogdescription' => $this->checkText($value),
|
||||
'WPLANG' => $this->checkLanguage($value),
|
||||
'timezone_string' => $this->checkTimezone($value),
|
||||
'date_format', 'time_format' => $this->checkFormat($value),
|
||||
'show_on_front' => $this->checkShowOnFront($value, $pending),
|
||||
'page_on_front', 'page_for_posts' => $this->checkPage($key, $value, $pending),
|
||||
'posts_per_page' => $this->checkPostsPerPage($value),
|
||||
'default_comment_status', 'default_ping_status' => $this->checkOpenClosed($value),
|
||||
'permalink_structure' => $this->checkPermalink($value),
|
||||
'site_icon' => $this->checkSiteIcon($value),
|
||||
};
|
||||
}
|
||||
|
||||
public function normalize(string $key, mixed $value): mixed
|
||||
{
|
||||
if ($key === 'WPLANG' && $value === 'en_US') {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function checkText(mixed $value): ?string
|
||||
{
|
||||
if (is_string($value) && mb_strlen($value) <= 200) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'Text bis 200 Zeichen erwartet.';
|
||||
}
|
||||
|
||||
private function checkLanguage(mixed $value): ?string
|
||||
{
|
||||
if ($value === 'en_US' || $value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$installed = get_available_languages();
|
||||
if (is_string($value) && in_array($value, $installed, true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return sprintf('Sprache nicht installiert; verfügbar: en_US, %s.', implode(', ', $installed));
|
||||
}
|
||||
|
||||
private function checkTimezone(mixed $value): ?string
|
||||
{
|
||||
if (is_string($value) && in_array($value, timezone_identifiers_list(), true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'Zeitzonen-Kennung wie Europe/Berlin erwartet.';
|
||||
}
|
||||
|
||||
private function checkFormat(mixed $value): ?string
|
||||
{
|
||||
if (is_string($value) && trim($value) !== '' && mb_strlen($value) <= 50) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'Nicht leeres Format bis 50 Zeichen erwartet.';
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $pending */
|
||||
private function checkShowOnFront(mixed $value, array $pending): ?string
|
||||
{
|
||||
if ($value === 'posts') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($value !== 'page') {
|
||||
return 'posts oder page erwartet.';
|
||||
}
|
||||
|
||||
$front = (int) ($pending['page_on_front'] ?? get_option('page_on_front'));
|
||||
if ($front > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'Für page zuerst page_on_front setzen (im selben Aufruf möglich).';
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $pending */
|
||||
private function checkPage(string $key, mixed $value, array $pending): ?string
|
||||
{
|
||||
if (! is_int($value) || $value < 0) {
|
||||
return 'Seiten-ID (0 = keine) erwartet.';
|
||||
}
|
||||
|
||||
if ($value === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$page = get_post($value);
|
||||
if (! $page instanceof WP_Post || $page->post_type !== 'page' || $page->post_status !== 'publish') {
|
||||
return sprintf('%d ist keine veröffentlichte Seite.', $value);
|
||||
}
|
||||
|
||||
$other = $key === 'page_on_front' ? 'page_for_posts' : 'page_on_front';
|
||||
$otherValue = (int) ($pending[$other] ?? get_option($other));
|
||||
if ($otherValue === $value) {
|
||||
return 'Startseite und Beitragsseite müssen verschiedene Seiten sein.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function checkPostsPerPage(mixed $value): ?string
|
||||
{
|
||||
if (is_int($value) && $value >= 1 && $value <= 100) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'Ganzzahl von 1 bis 100 erwartet.';
|
||||
}
|
||||
|
||||
private function checkOpenClosed(mixed $value): ?string
|
||||
{
|
||||
if (in_array($value, ['open', 'closed'], true)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'open oder closed erwartet.';
|
||||
}
|
||||
|
||||
private function checkPermalink(mixed $value): ?string
|
||||
{
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
is_string($value)
|
||||
&& str_starts_with($value, '/')
|
||||
&& str_contains($value, '%')
|
||||
&& mb_strlen($value) <= 200
|
||||
&& preg_match('/\s/', $value) !== 1
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'Leer oder eine Struktur wie /%postname%/ erwartet.';
|
||||
}
|
||||
|
||||
private function checkSiteIcon(mixed $value): ?string
|
||||
{
|
||||
if (! is_int($value) || $value < 0) {
|
||||
return 'Anhang-ID (0 = keins) erwartet.';
|
||||
}
|
||||
|
||||
if ($value === 0 || wp_attachment_is_image($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return sprintf('%d ist kein Bild der Mediathek.', $value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Settings;
|
||||
|
||||
use LIT\MCP\Abilities\Ability;
|
||||
use LIT\MCP\Abilities\Errors;
|
||||
use WP_Error;
|
||||
|
||||
final class WpSettingsGetAbility implements Ability
|
||||
{
|
||||
public function __construct(private SettingsWhitelist $whitelist)
|
||||
{
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'lit/wp-settings-get';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'WordPress-Einstellungen lesen';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Liest die freigegebenen WordPress-Einstellungen (Allgemein, Lesen, Diskussion, Permalinks, '
|
||||
. 'Website-Icon) mit Typ und Beschreibung. Ändern mit lit-wp-settings-update.';
|
||||
}
|
||||
|
||||
public function inputSchema(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => ['group' => ['type' => 'string', 'enum' => SettingsWhitelist::GROUPS]],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function outputSchema(): ?array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'settings' => [
|
||||
'type' => 'array',
|
||||
'items' => [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'key' => ['type' => 'string'],
|
||||
'group' => ['type' => 'string'],
|
||||
'type' => ['type' => 'string'],
|
||||
'value' => ['type' => ['string', 'integer']],
|
||||
'description' => ['type' => 'string'],
|
||||
],
|
||||
'required' => ['key', 'group', 'type', 'value', 'description'],
|
||||
],
|
||||
],
|
||||
],
|
||||
'required' => ['settings'],
|
||||
];
|
||||
}
|
||||
|
||||
public function annotations(): array
|
||||
{
|
||||
return ['readonly' => true, 'destructive' => false, 'idempotent' => true];
|
||||
}
|
||||
|
||||
public function isDirect(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function permission(array $input): bool|WP_Error
|
||||
{
|
||||
return current_user_can('manage_options')
|
||||
? true
|
||||
: Errors::forbidden('Keine Berechtigung für WordPress-Einstellungen (manage_options).');
|
||||
}
|
||||
|
||||
public function execute(array $input): mixed
|
||||
{
|
||||
$group = isset($input['group']) ? (string) $input['group'] : '';
|
||||
$settings = [];
|
||||
foreach (SettingsWhitelist::SETTINGS as $key => [$settingGroup, $type, $description]) {
|
||||
if ($group !== '' && $settingGroup !== $group) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$settings[] = [
|
||||
'key' => $key,
|
||||
'group' => $settingGroup,
|
||||
'type' => $type,
|
||||
'value' => $this->whitelist->current($key),
|
||||
'description' => $description,
|
||||
];
|
||||
}
|
||||
|
||||
return ['settings' => $settings];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace LIT\MCP\Integrations\WordPress\Settings;
|
||||
|
||||
use LIT\MCP\Abilities\Ability;
|
||||
use LIT\MCP\Abilities\Errors;
|
||||
use LIT\MCP\Abilities\JsonMap;
|
||||
use LIT\MCP\Abilities\ToolResult;
|
||||
use LIT\MCP\ChangeLog\ChangeLog;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
use WP_Error;
|
||||
|
||||
/**
|
||||
* lit/wp-settings-update: writes whitelisted WordPress options, all or nothing.
|
||||
*
|
||||
* Every value is validated against SettingsWhitelist first; nothing is written if any
|
||||
* value is invalid. "At least one setting" is enforced here in code rather than with the
|
||||
* JSON Schema keyword `minProperties`: the plan's Global Constraints list only the JSON
|
||||
* Schema keywords rest_validate_value_from_schema() checks for this project
|
||||
* (type/properties/required/items/enum/minimum/maximum/minLength/maxLength/pattern/
|
||||
* minItems/maxItems/additionalProperties) and `minProperties` is not among them, even
|
||||
* though WordPress core's REST validator does support it (controller ruling C6).
|
||||
*/
|
||||
final class WpSettingsUpdateAbility implements Ability
|
||||
{
|
||||
public function __construct(private SettingsWhitelist $whitelist, private ChangeLog $log)
|
||||
{
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'lit/wp-settings-update';
|
||||
}
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return 'WordPress-Einstellungen ändern';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Ändert freigegebene WordPress-Einstellungen (Schlüssel siehe lit-wp-settings-get). Alle Werte '
|
||||
. 'werden vorher geprüft – bei einem Fehler wird nichts gespeichert. previous enthält die alten Werte. '
|
||||
. 'Gesperrt: admin_email, users_can_register, default_role, siteurl, home.';
|
||||
}
|
||||
|
||||
public function inputSchema(): array
|
||||
{
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'settings' => [
|
||||
'type' => 'object',
|
||||
'description' => 'Schlüssel → neuer Wert, mindestens einer, z. B. {"blogname": "Praxis Muster"}.',
|
||||
],
|
||||
],
|
||||
'required' => ['settings'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
public function outputSchema(): ?array
|
||||
{
|
||||
return ToolResult::schema(['previous' => ['type' => 'object']], ['previous']);
|
||||
}
|
||||
|
||||
public function annotations(): array
|
||||
{
|
||||
return ['readonly' => false, 'destructive' => false, 'idempotent' => true];
|
||||
}
|
||||
|
||||
public function isDirect(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function permission(array $input): bool|WP_Error
|
||||
{
|
||||
return current_user_can('manage_options')
|
||||
? true
|
||||
: Errors::forbidden('Keine Berechtigung für WordPress-Einstellungen (manage_options).');
|
||||
}
|
||||
|
||||
public function execute(array $input): mixed
|
||||
{
|
||||
$settings = is_array($input['settings'] ?? null) ? $input['settings'] : [];
|
||||
if ($settings === []) {
|
||||
return Errors::invalidInput('Keine Einstellungen angegeben.', ['settings' => 'mindestens ein Schlüssel']);
|
||||
}
|
||||
|
||||
$errors = $this->validateAll($settings);
|
||||
if ($errors !== []) {
|
||||
return Errors::invalidInput(
|
||||
'Einstellungen ungültig; nichts wurde gespeichert.',
|
||||
$errors,
|
||||
'Werte gemäß fields korrigieren; aktuelle Werte über lit-wp-settings-get.'
|
||||
);
|
||||
}
|
||||
|
||||
return $this->write($settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $settings
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function validateAll(array $settings): array
|
||||
{
|
||||
$errors = [];
|
||||
foreach ($settings as $key => $value) {
|
||||
$error = $this->whitelist->validate((string) $key, $value, $settings);
|
||||
if ($error !== null) {
|
||||
$errors[(string) $key] = $error;
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* All values are already known-valid; writes only the ones that actually change.
|
||||
* If a write fails partway through, the already-written keys are restored to their
|
||||
* previous values so the call stays all-or-nothing.
|
||||
*
|
||||
* @param array<string, mixed> $settings
|
||||
*/
|
||||
private function write(array $settings): array|WP_Error
|
||||
{
|
||||
$previous = [];
|
||||
foreach ($settings as $key => $value) {
|
||||
$previous[(string) $key] = $this->whitelist->current((string) $key);
|
||||
}
|
||||
|
||||
$changed = [];
|
||||
try {
|
||||
foreach ($settings as $key => $value) {
|
||||
$key = (string) $key;
|
||||
if ($previous[$key] === $value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->writeOne($key, $value);
|
||||
$changed[] = $key;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
return $this->fail($changed, $previous, $e);
|
||||
}
|
||||
|
||||
if ($changed === []) {
|
||||
return ToolResult::ok('Keine Änderung – alle Werte waren bereits gesetzt.')
|
||||
->with('previous', JsonMap::of($previous))
|
||||
->toArray();
|
||||
}
|
||||
|
||||
$summary = 'Einstellungen geändert: ' . implode(', ', $changed);
|
||||
$logId = $this->log->record($this->name(), 'option', implode(',', $changed), $summary);
|
||||
|
||||
$result = ToolResult::ok($summary . '.');
|
||||
foreach ($changed as $key) {
|
||||
$result->changed($key, 'option', 'updated', SettingsWhitelist::SETTINGS[$key][2]);
|
||||
}
|
||||
|
||||
return $result->logId($logId)->with('previous', JsonMap::of($previous))->toArray();
|
||||
}
|
||||
|
||||
private function writeOne(string $key, mixed $value): void
|
||||
{
|
||||
if ($key === 'permalink_structure') {
|
||||
$this->setPermalinkStructure((string) $value);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (update_option($key, $this->whitelist->normalize($key, $value)) === false) {
|
||||
throw new RuntimeException(sprintf('update_option(%s) returned false', $key));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A write failed; restores the keys already written to their previous values and
|
||||
* reports write_failed (fully restored) or partial_write (some keys could not be
|
||||
* restored – the client is told which, so it can check and correct them).
|
||||
*
|
||||
* @param list<string> $changed Keys written so far, in write order.
|
||||
* @param array<string, mixed> $previous Their values before this call.
|
||||
*/
|
||||
private function fail(array $changed, array $previous, Throwable $cause): WP_Error
|
||||
{
|
||||
$stuck = [];
|
||||
foreach (array_reverse($changed) as $key) {
|
||||
try {
|
||||
$this->writeOne($key, $previous[$key]);
|
||||
} catch (Throwable $e) {
|
||||
$stuck[] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
error_log( // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
sprintf('[wp-lit-mcp] wp-settings-update failed: %s', $cause)
|
||||
);
|
||||
|
||||
if ($stuck === []) {
|
||||
return Errors::writeFailed('Eine Einstellung konnte nicht gespeichert werden.');
|
||||
}
|
||||
|
||||
return Errors::partialWrite(
|
||||
'Eine Einstellung konnte nicht gespeichert werden.',
|
||||
null,
|
||||
null,
|
||||
sprintf(
|
||||
'Möglicherweise auf dem neuen, nicht vollständigen Stand: %s.',
|
||||
implode(', ', $stuck)
|
||||
),
|
||||
'Aktuelle Werte über lit-wp-settings-get prüfen und ggf. erneut auf die gewünschten Werte setzen.'
|
||||
);
|
||||
}
|
||||
|
||||
private function setPermalinkStructure(string $structure): void
|
||||
{
|
||||
global $wp_rewrite;
|
||||
$wp_rewrite->set_permalink_structure($structure);
|
||||
flush_rewrite_rules();
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,9 @@ use LIT\MCP\Integrations\WordPress\Revisions\RevisionsListAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\ContentSchema;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\FieldValidator;
|
||||
use LIT\MCP\Integrations\WordPress\Schema\TermAssigner;
|
||||
use LIT\MCP\Integrations\WordPress\Settings\SettingsWhitelist;
|
||||
use LIT\MCP\Integrations\WordPress\Settings\WpSettingsGetAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Settings\WpSettingsUpdateAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Status\PostCloner;
|
||||
use LIT\MCP\Integrations\WordPress\Status\PostDuplicateAbility;
|
||||
use LIT\MCP\Integrations\WordPress\Status\PostPublishAbility;
|
||||
@@ -58,6 +61,7 @@ final class WordPressIntegration implements Integration
|
||||
$presenter = new PostPresenter($this->schema);
|
||||
$writer = new PostWriter($this->schema, new FieldValidator(), new TermAssigner());
|
||||
$cloner = new PostCloner();
|
||||
$whitelist = new SettingsWhitelist();
|
||||
|
||||
return [
|
||||
new ContentTypesAbility($this->schema),
|
||||
@@ -78,6 +82,8 @@ final class WordPressIntegration implements Integration
|
||||
new MenuCreateAbility($this->log),
|
||||
new MenuSetItemsAbility(new MenuWriter(), new MenuOperations(), $this->log),
|
||||
new MenuAssignLocationAbility($this->log),
|
||||
new WpSettingsGetAbility($whitelist),
|
||||
new WpSettingsUpdateAbility($whitelist, $this->log),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user