PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.1.4
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.1.4
1.3.3 1.3.2 1.3.1 1.3.0 1.2.4 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 1.1.0 1.1.1 1.1.2 1.1.3 1.1.4 1.1.5 1.1.6 1.1.7 1.1.8 All 29 releases
xspeed / includes / modules / Mcp / Mcp_Tools.php

Mcp_Tools.php in xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN 1.1.4, at includes/modules/Mcp/Mcp_Tools.php

1,547 lines 56.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * MCP tool registry — the single source of truth for the tools xSpeed
4 * exposes to AI assistants.
5 *
6 * Each tool declares an MCP-style descriptor (name, description, JSON
7 * Schema inputSchema) and a handler that runs against the Free engine.
8 * Consumed by BOTH:
9 * - Mcp_Server (the per-site JSON-RPC endpoint at /xspeed/mcp), and
10 * - McpModule's REST tool routes (the optional hosted-broker path),
11 * so the two transports can never drift.
12 *
13 * Handlers take an associative array of already-decoded arguments and
14 * return either a plain array (serialized to JSON in the MCP result) or
15 * a WP_Error (surfaced as an MCP tool error).
16 *
17 * The plugin adds ZERO cache logic here — every handler is a thin proxy
18 * to Cache / Settings / Settings_Manager / Server / Admin / Pro_Audit /
19 * Cache_Benchmark.
20 *
21 * @package XSpeed
22 */
23
24 declare(strict_types=1);
25
26 namespace XSpeed\Modules\Mcp;
27
28 use XSpeed\Cache;
29 use XSpeed\Server;
30 use XSpeed\Admin;
31 use XSpeed\Settings;
32 use XSpeed\Settings_Manager;
33 use XSpeed\Pro_Audit;
34 use XSpeed\Cache_Benchmark;
35
36 defined( 'ABSPATH' ) || exit;
37
38 final class Mcp_Tools {
39
40 /** Valid cache purge types. */
41 public const PURGE_TYPES = array( 'all', 'page', 'assets', 'object', 'rest' );
42
43 /**
44 * Per-call read-only override. Null means "defer to the pairing token's
45 * scope" (the JSON-RPC path that predates OAuth). true/false is set by
46 * Mcp_Server when an OAuth access token (with its own scope) authorized
47 * the request, so a read-only OAuth grant is enforced even though the
48 * pairing token may be read-write (or absent).
49 *
50 * @var bool|null
51 */
52 private static $read_only_override = null;
53
54 /**
55 * Set the active credential's read-only state for the current request.
56 * Passing null clears the override (back to the pairing-token default).
57 *
58 * @param bool|null $read_only Whether the active credential is read-only.
59 */
60 public static function set_read_only_override( ?bool $read_only ): void {
61 self::$read_only_override = $read_only;
62 }
63
64 /**
65 * Whether the active MCP credential is limited to read-only tools. Uses
66 * the per-call override when set, else the pairing token's scope.
67 */
68 private static function is_read_only(): bool {
69 if ( null !== self::$read_only_override ) {
70 return self::$read_only_override;
71 }
72 return Mcp_Pairing::is_read_only();
73 }
74
75 /**
76 * Per-call `configure` grant. Writing credential/secret fields over MCP is
77 * gated on this and it is OFF by default — even a write-scoped connection
78 * cannot rewrite an API token or password unless it was granted the
79 * explicit `configure` scope. Null means "no per-call grant" (the pairing
80 * token / JSON-RPC path), where it falls back to a filter. (#116)
81 *
82 * @var bool|null
83 */
84 private static $configure_override = null;
85
86 /**
87 * Set whether the active credential may write secret fields (the OAuth
88 * `configure` scope). Passing null clears it back to the filter default.
89 *
90 * @param bool|null $can_configure Whether the credential carries `configure`.
91 */
92 public static function set_configure_override( ?bool $can_configure ): void {
93 self::$configure_override = $can_configure;
94 }
95
96 /**
97 * Whether the active MCP credential may write credential/secret fields.
98 * Uses the per-call override (OAuth `configure` scope) when set; otherwise
99 * the `xspeed_mcp_allow_credential_writes` filter, which defaults to false
100 * so credential writes are off by default on every connection — including
101 * the pairing token. A site owner who wants an agent to manage credentials
102 * opts in by returning true from that filter. (#116)
103 */
104 public static function can_configure(): bool {
105 if ( null !== self::$configure_override ) {
106 return self::$configure_override;
107 }
108 /**
109 * Allow MCP connections to write credential (secret) fields. Off by
110 * default; see docs/MCP-SERVER.md. Applies to pairing-token connections
111 * and any OAuth grant lacking the `configure` scope.
112 *
113 * @param bool $allow Whether credential writes over MCP are permitted.
114 */
115 return (bool) apply_filters( 'xspeed_mcp_allow_credential_writes', false );
116 }
117
118 /**
119 * Full tool catalog: name => descriptor. `handler` is a callable
120 * ( array $args ) : array|\WP_Error. `write` marks tools that mutate
121 * state (used for read-only scope enforcement).
122 *
123 * @return array<string, array{description:string, inputSchema:array, handler:callable, write:bool}>
124 */
125 public static function catalog(): array {
126 $catalog = array(
127 'get_cache_status' => array(
128 'description' => 'Get cache status for this WordPress site: whether caching is enabled, cache stats (cached pages, size, hit ratio, last purge), and the detected web server.',
129 'inputSchema' => self::object_schema( array(), array() ),
130 'write' => false,
131 'handler' => array( self::class, 'get_cache_status' ),
132 ),
133 'list_modules' => array(
134 'description' => 'List all xSpeed modules (free and Pro) with their settings schema and status.',
135 'inputSchema' => self::object_schema( array(), array() ),
136 'write' => false,
137 'handler' => array( self::class, 'list_modules' ),
138 ),
139 'run_benchmark' => array(
140 'description' => 'Run a before/after cache benchmark on the home page and return the timings. Each side reports bytes (decoded payload) and bytes_transferred (compressed wire size).',
141 'inputSchema' => self::object_schema( array(), array() ),
142 'write' => false,
143 'handler' => array( self::class, 'run_benchmark' ),
144 ),
145 'get_pro_audit' => array(
146 'description' => 'Personalized list of Pro features that would benefit THIS site, from its current settings and cache stats.',
147 'inputSchema' => self::object_schema( array(), array() ),
148 'write' => false,
149 'handler' => array( self::class, 'get_pro_audit' ),
150 ),
151 'purge_cache' => array(
152 'description' => 'Purge the site cache. "type" selects what to purge: all, page, assets, object, or rest. Defaults to all.',
153 'inputSchema' => self::object_schema(
154 array(
155 'type' => array(
156 'type' => 'string',
157 'enum' => self::PURGE_TYPES,
158 'description' => 'What to purge. Defaults to "all".',
159 ),
160 ),
161 array()
162 ),
163 'write' => true,
164 'handler' => array( self::class, 'purge_cache' ),
165 ),
166 'toggle_cache' => array(
167 'description' => 'Enable or disable page caching. Installs/removes the cache drop-in and WP_CACHE constant as needed.',
168 'inputSchema' => self::object_schema(
169 array(
170 'enabled' => array(
171 'type' => 'boolean',
172 'description' => 'true to enable caching, false to disable.',
173 ),
174 ),
175 array( 'enabled' )
176 ),
177 'write' => true,
178 'handler' => array( self::class, 'toggle_cache' ),
179 ),
180 'get_settings' => array(
181 'description' => 'Read the settings for a given xSpeed module (e.g. "minify", "gzip"). Returns schema-validated values.',
182 'inputSchema' => self::object_schema(
183 array(
184 'module' => array(
185 'type' => 'string',
186 'description' => 'The module slug, e.g. "minify".',
187 ),
188 ),
189 array( 'module' )
190 ),
191 'write' => false,
192 'handler' => array( self::class, 'get_settings' ),
193 ),
194 'update_settings' => array(
195 'description' => 'Update settings for a given xSpeed module. "values" is an object of setting keys to new values; unknown keys are stripped and invalid values rejected by the module schema.',
196 'inputSchema' => self::object_schema(
197 array(
198 'module' => array(
199 'type' => 'string',
200 'description' => 'The module slug, e.g. "minify".',
201 ),
202 'values' => array(
203 'type' => 'object',
204 'description' => 'Map of setting keys to new values.',
205 ),
206 ),
207 array( 'module', 'values' )
208 ),
209 'write' => true,
210 'handler' => array( self::class, 'update_settings' ),
211 ),
212 // --- Promoted high-value actions: dedicated typed tools so the AI
213 // calls them directly (no run_command hop). Each is a thin wrapper
214 // over Cli_Bridge, so Free tools can drive Pro actions (psi, ccss)
215 // without a cross-repo class reference, and none can drift from the
216 // CLI. ---
217 'purge_cloudflare' => array(
218 'description' => 'Purge the Cloudflare edge cache for this site (requires Cloudflare connected in the Cloudflare module).',
219 'inputSchema' => self::object_schema( array(), array() ),
220 'write' => true,
221 'handler' => array( self::class, 'purge_cloudflare' ),
222 ),
223 'scan_database' => array(
224 'description' => 'Scan the database for bloat (post revisions, auto-drafts, trashed posts, spam comments, expired transients, orphaned meta) without deleting anything.',
225 'inputSchema' => self::object_schema( array(), array() ),
226 'write' => false,
227 'handler' => array( self::class, 'scan_database' ),
228 ),
229 'clean_database' => array(
230 'description' => 'Clean database bloat. Removes the categories currently enabled in the Database module settings. Destructive — run scan_database first to preview.',
231 'inputSchema' => self::object_schema( array(), array() ),
232 'write' => true,
233 'handler' => array( self::class, 'clean_database' ),
234 ),
235 'flush_object_cache' => array(
236 'description' => 'Flush the persistent object cache (Redis / Memcached), if enabled.',
237 'inputSchema' => self::object_schema( array(), array() ),
238 'write' => true,
239 'handler' => array( self::class, 'flush_object_cache' ),
240 ),
241 'start_preloader' => array(
242 'description' => 'Start the cache preloader — crawls the sitemap to warm the page cache in the background.',
243 'inputSchema' => self::object_schema( array(), array() ),
244 'write' => true,
245 'handler' => array( self::class, 'start_preloader' ),
246 ),
247 'run_pagespeed' => array(
248 'description' => 'Run an external performance audit (PageSpeed Insights, or GTmetrix when configured) and return the score + Core Web Vitals. Defaults to the site home page, mobile strategy. Requires external scores to be enabled in settings — the plugin makes no outbound calls otherwise.',
249 'inputSchema' => self::object_schema(
250 array(
251 'url' => array(
252 'type' => 'string',
253 'description' => 'URL to audit. Defaults to the site home page.',
254 ),
255 'strategy' => array(
256 'type' => 'string',
257 'enum' => array( 'mobile', 'desktop' ),
258 'description' => 'Audit strategy. Defaults to "mobile".',
259 ),
260 'force' => array(
261 'type' => 'boolean',
262 'description' => 'Re-run even when a recent cached result exists. Use after a change you want measured immediately.',
263 ),
264 ),
265 array()
266 ),
267 'write' => false,
268 'handler' => array( self::class, 'run_pagespeed' ),
269 ),
270 'generate_critical_css' => array(
271 'description' => 'Generate above-the-fold Critical CSS for the site (Pro). Calls the external generator and stores the result.',
272 'inputSchema' => self::object_schema( array(), array() ),
273 'write' => true,
274 'handler' => array( self::class, 'generate_critical_css' ),
275 ),
276 'get_health' => array(
277 'description' => 'Full health diagnostics: every Health check (drop-in, WP_CACHE, server rewrite, expiry-vs-preload, Set-Cookie poisoning, conflicts), cache stats, hourly hit/miss buckets, the daily hit-ratio series, and recent activity. The single best first call when diagnosing a low hit ratio.',
278 'inputSchema' => self::object_schema( array(), array() ),
279 'write' => false,
280 'handler' => array( self::class, 'get_health' ),
281 ),
282 'get_benchmark_history' => array(
283 'description' => 'Stored benchmark runs (oldest to newest: timestamps, uncached/cached ms, savings, transfer bytes) plus recent settings-change events for correlating a change with its performance effect.',
284 'inputSchema' => self::object_schema(
285 array(
286 'limit' => array(
287 'type' => 'integer',
288 'description' => 'Max runs to return (default 100).',
289 ),
290 ),
291 array()
292 ),
293 'write' => false,
294 'handler' => array( self::class, 'get_benchmark_history' ),
295 ),
296 'get_score_history' => array(
297 'description' => 'Stored EXTERNAL audit runs (PageSpeed Insights / GTmetrix): score, Core Web Vitals (LCP/FCP/CLS/TBT/SI/TTFB), which tool ran it, and the report link where one exists. Read-only — returns what this site already measured and never starts a new audit. Use run_pagespeed to actually run one.',
298 'inputSchema' => self::object_schema(
299 array(
300 'limit' => array(
301 'type' => 'integer',
302 'description' => 'Max runs to return, newest first (default 100).',
303 ),
304 ),
305 array()
306 ),
307 'write' => false,
308 'handler' => array( self::class, 'get_score_history' ),
309 ),
310 // --- Actions promoted out of the generated `xspeed_*` aliases.
311 // Each was previously reachable ONLY as an `action` string on a
312 // coarse generated tool that was marked write regardless, so a
313 // read-only connection lost the read ones. Typed here with an
314 // honest kind so the AI stops guessing and the deny-list has one
315 // name per action. ---
316 'get_cache_inventory' => array(
317 'description' => 'Inspect what is actually in the page cache: which pages are cached and how old they are, or where the disk usage goes. Read-only.',
318 'inputSchema' => self::object_schema(
319 array(
320 'detail' => array(
321 'type' => 'string',
322 'enum' => array( 'pages', 'size' ),
323 'description' => '"pages" lists cached pages and their age; "size" breaks down disk usage. Defaults to "pages".',
324 ),
325 'limit' => array(
326 'type' => 'string',
327 'description' => 'Max rows to return (pages only).',
328 ),
329 ),
330 array()
331 ),
332 'write' => false,
333 'handler' => array( self::class, 'get_cache_inventory' ),
334 ),
335 'get_purge_log' => array(
336 'description' => 'Recent cache purges and what triggered each one. Use it to explain why a page stopped being cached. Read-only.',
337 'inputSchema' => self::object_schema(
338 array(
339 'limit' => array(
340 'type' => 'string',
341 'description' => 'Max entries to return.',
342 ),
343 ),
344 array()
345 ),
346 'write' => false,
347 'handler' => array( self::class, 'get_purge_log' ),
348 ),
349 'recheck_rewrite_rules' => array(
350 'description' => 'Re-verify the server rewrite rules that route requests to the cache, and repair them if they drifted.',
351 'inputSchema' => self::object_schema( array(), array() ),
352 'write' => true,
353 'handler' => array( self::class, 'recheck_rewrite_rules' ),
354 ),
355 'set_cloudflare_dev_mode' => array(
356 'description' => 'Turn Cloudflare development mode on or off. On bypasses the edge cache for ~3 hours so origin changes show immediately.',
357 'inputSchema' => self::object_schema(
358 array(
359 'enabled' => array(
360 'type' => 'boolean',
361 'description' => 'true turns development mode on, false turns it off.',
362 ),
363 ),
364 array( 'enabled' )
365 ),
366 'write' => true,
367 'handler' => array( self::class, 'set_cloudflare_dev_mode' ),
368 ),
369 'optimize_database' => array(
370 'description' => 'Run table optimization on the WordPress database (reclaims space after cleanup). Separate from clean_database, which deletes bloat rows.',
371 'inputSchema' => self::object_schema( array(), array() ),
372 'write' => true,
373 'handler' => array( self::class, 'optimize_database' ),
374 ),
375 'get_object_cache_status' => array(
376 'description' => 'Object cache state: whether the drop-in is installed, which backend is configured, and the server snippet needed to enable it. Read-only.',
377 'inputSchema' => self::object_schema(
378 array(
379 'detail' => array(
380 'type' => 'string',
381 'enum' => array( 'status', 'snippet' ),
382 'description' => '"status" reports the current state; "snippet" returns the server config to enable it. Defaults to "status".',
383 ),
384 ),
385 array()
386 ),
387 'write' => false,
388 'handler' => array( self::class, 'get_object_cache_status' ),
389 ),
390 'toggle_object_cache' => array(
391 'description' => 'Enable or disable the object cache drop-in. Verify the backend with test_object_cache first — enabling against an unreachable server slows every request.',
392 'inputSchema' => self::object_schema(
393 array(
394 'enabled' => array(
395 'type' => 'boolean',
396 'description' => 'true installs the drop-in, false removes it.',
397 ),
398 ),
399 array( 'enabled' )
400 ),
401 'write' => true,
402 'handler' => array( self::class, 'toggle_object_cache' ),
403 ),
404 'manage_critical_css' => array(
405 'description' => 'List the stored Critical CSS entries, or clear them so they regenerate. Use generate_critical_css to create them.',
406 'inputSchema' => self::object_schema(
407 array(
408 'action' => array(
409 'type' => 'string',
410 'enum' => array( 'list', 'clear' ),
411 'description' => '"list" returns what is stored; "clear" deletes it.',
412 ),
413 ),
414 array( 'action' )
415 ),
416 'write' => true,
417 'handler' => array( self::class, 'manage_critical_css' ),
418 ),
419 'get_preloader_status' => array(
420 'description' => 'Cache preloader progress: whether a run is active, how far through the URL list it is. Read-only.',
421 'inputSchema' => self::object_schema( array(), array() ),
422 'write' => false,
423 'handler' => array( self::class, 'get_preloader_status' ),
424 ),
425 'stop_preloader' => array(
426 'description' => 'Stop a running cache preload. Safe mid-run — already-warmed pages stay cached.',
427 'inputSchema' => self::object_schema( array(), array() ),
428 'write' => true,
429 'handler' => array( self::class, 'stop_preloader' ),
430 ),
431 'purge_url' => array(
432 'description' => 'Purge the cache for ONE URL only (all its variants: device buckets, trailing-slash forms, static-tree copy). Surgical alternative to purge_cache when a single page changed.',
433 'inputSchema' => self::object_schema(
434 array(
435 'url' => array(
436 'type' => 'string',
437 'description' => 'Absolute URL or site-relative path, e.g. "https://site.com/about/" or "/about/".',
438 ),
439 ),
440 array( 'url' )
441 ),
442 'write' => true,
443 'handler' => array( self::class, 'purge_url' ),
444 ),
445 'test_object_cache' => array(
446 'description' => 'Live connect + read/write probe of the configured Redis/Memcached backend using the saved Object Cache settings. Verifies the credentials actually work — writing settings alone does not.',
447 'inputSchema' => self::object_schema( array(), array() ),
448 'write' => false,
449 'handler' => array( self::class, 'test_object_cache' ),
450 ),
451 'cloudflare_verify' => array(
452 'description' => 'Verify the saved Cloudflare credentials against the Cloudflare API (token/zone check). Read-only — use purge_cloudflare to purge the edge.',
453 'inputSchema' => self::object_schema( array(), array() ),
454 'write' => false,
455 'handler' => array( self::class, 'cloudflare_verify' ),
456 ),
457 'list_commands' => array(
458 'description' => 'List every xSpeed command that run_command can invoke (name, description, module, options). Use this to discover the full action surface beyond the curated + dedicated tools.',
459 'inputSchema' => self::object_schema( array(), array() ),
460 'write' => false,
461 'handler' => array( self::class, 'list_commands' ),
462 ),
463 'run_command' => array(
464 'description' => 'Run any xSpeed command — the full CLI surface (~50 commands across every module: cache, cloudflare, database, critical/unused CSS, pagespeed, images, migration, preloader, object cache, analytics, RUM, smart-* and more). Call list_commands first to discover names + options. Examples: run_command("cloudflare purge"), run_command("database clean"), run_command("psi", {}, {"url":"https://site.com","strategy":"mobile"}).',
465 'inputSchema' => self::object_schema(
466 array(
467 'command' => array(
468 'type' => 'string',
469 'description' => 'Command name, e.g. "cloudflare purge" or "database scan" (the "xspeed " prefix is optional).',
470 ),
471 'args' => array(
472 'type' => 'array',
473 'description' => 'Positional arguments, if the command takes any.',
474 'items' => array( 'type' => 'string' ),
475 ),
476 'options' => array(
477 'type' => 'object',
478 'description' => 'Named options / flags, e.g. { "url": "https://site.com", "strategy": "mobile", "force": true }.',
479 ),
480 ),
481 array( 'command' )
482 ),
483 'write' => true,
484 'handler' => array( self::class, 'run_command' ),
485 ),
486 );
487
488 // Dedicated tools that wrap a command only present when a given
489 // module is active (e.g. Pro): drop them if the command isn't
490 // registered, so we never advertise a tool that always fails. The
491 // action stays reachable via run_command if the command exists.
492 $conditional = array(
493 'generate_critical_css' => 'xspeed ccss',
494 'purge_cloudflare' => 'xspeed cf',
495 'cloudflare_verify' => 'xspeed cf',
496 'flush_object_cache' => 'xspeed objcache',
497 'test_object_cache' => 'xspeed objcache',
498 'start_preloader' => 'xspeed preloader',
499 'scan_database' => 'xspeed db',
500 'clean_database' => 'xspeed db',
501 'purge_url' => 'xspeed cache',
502 'get_cache_inventory' => 'xspeed cache',
503 'get_purge_log' => 'xspeed cache',
504 'recheck_rewrite_rules' => 'xspeed cache',
505 'set_cloudflare_dev_mode' => 'xspeed cf',
506 'optimize_database' => 'xspeed db',
507 'get_object_cache_status' => 'xspeed objcache',
508 'toggle_object_cache' => 'xspeed objcache',
509 'manage_critical_css' => 'xspeed ccss',
510 'get_preloader_status' => 'xspeed preloader',
511 'stop_preloader' => 'xspeed preloader',
512 // These three have no module dependency — get_settings /
513 // run_pagespeed / get_health are always present — but they belong
514 // here so the generator skips their commands too. $conditional is
515 // read for BOTH purposes: drop a tool when its command is gone,
516 // and never generate an alias for a command a tool already covers.
517 'get_settings' => 'xspeed settings',
518 'update_settings' => 'xspeed settings',
519 'run_pagespeed' => 'xspeed psi',
520 'get_health' => 'xspeed health',
521 'get_score_history' => 'xspeed score',
522 );
523 $commands = Cli_Bridge::commands();
524 foreach ( $conditional as $tool => $command ) {
525 if ( ! isset( $commands[ $command ] ) ) {
526 unset( $catalog[ $tool ] );
527 }
528 }
529
530 /*
531 * One dedicated tool per xSpeed CLI command, generated from the same
532 * Cli_Bridge catalog the CLI registers from — so the AI can reach the
533 * long tail without the list_commands -> run_command hop, and the
534 * generated set can never drift from the CLI.
535 *
536 * Commands already covered by a typed tool above are SKIPPED. The
537 * `isset()` guard below only catches NAME collisions, and a generated
538 * name never collides — `xspeed cf` becomes `xspeed_cf`, which is not
539 * `purge_cloudflare`. So both used to ship: two tools for one action,
540 * with the generated one marked write even when it wrapped a read,
541 * and a per-tool permission on one name silently bypassable via the
542 * other. $conditional already maps every typed tool to its command;
543 * inverted, that IS the skip list.
544 */
545 foreach ( self::cli_generated_tools( array_flip( $conditional ) ) as $name => $spec ) {
546 if ( ! isset( $catalog[ $name ] ) ) {
547 $catalog[ $name ] = $spec;
548 }
549 }
550
551 return $catalog;
552 }
553
554 /**
555 * Generate one MCP tool per registered xSpeed CLI command. Each wraps
556 * Cli_Bridge::run(): the tool's `action` (the command's first positional,
557 * e.g. `verify`/`purge` for `xspeed cf`) plus any named options are passed
558 * straight through. Tool names are the command with the `xspeed ` prefix
559 * dropped and spaces -> underscores (`xspeed cf` -> `xspeed_cf`).
560 *
561 * @return array<string, array{description:string, inputSchema:array, write:bool, handler:callable}>
562 */
563 private static function cli_generated_tools( array $covered = array() ): array {
564 $tools = array();
565 foreach ( Cli_Bridge::commands() as $command => $spec ) {
566 // Already exposed as typed tools with real schemas and honest
567 // read/write kinds — generating a coarse alias too would give the
568 // AI two ways to do one thing and make a per-tool permission on
569 // the typed name bypassable via the generated one.
570 if ( isset( $covered[ $command ] ) ) {
571 continue;
572 }
573 $tool_name = self::cli_tool_name( $command );
574 if ( '' === $tool_name ) {
575 continue;
576 }
577
578 // Build the input schema from the command's synopsis: positional
579 // args become string properties (the first is usually the action,
580 // exposed with its allowed values as an enum); assoc args become
581 // named options.
582 $properties = array();
583 $required = array();
584 foreach ( $spec['synopsis'] as $arg ) {
585 if ( ! isset( $arg['name'] ) ) {
586 continue;
587 }
588 $arg_name = (string) $arg['name'];
589 $prop = array(
590 'type' => 'string',
591 'description' => isset( $arg['description'] ) ? (string) $arg['description'] : '',
592 );
593 if ( isset( $arg['options'] ) && is_array( $arg['options'] ) && ! empty( $arg['options'] ) ) {
594 $prop['enum'] = array_values( array_map( 'strval', $arg['options'] ) );
595 }
596 $properties[ $arg_name ] = $prop;
597 $is_optional = ! empty( $arg['optional'] );
598 $is_flag = isset( $arg['type'] ) && 'flag' === $arg['type'];
599 if ( ! $is_optional && ! $is_flag ) {
600 $required[] = $arg_name;
601 }
602 }
603
604 $description = '' !== $spec['shortdesc']
605 ? $spec['shortdesc']
606 : sprintf( 'Run the "%s" xSpeed command.', $command );
607
608 list( $write, $write_actions, $read_actions ) = self::cli_write_profile( $command, $spec['synopsis'] );
609
610 $tools[ $tool_name ] = array(
611 'description' => $description,
612 'inputSchema' => self::object_schema( $properties, $required ),
613 'write' => $write,
614 // The action values that mutate state. When set, read-only
615 // enforcement is per-ACTION (a read-only grant may still call
616 // the tool with a read action like "status"/"scan").
617 'write_actions' => $write_actions,
618 // The complement — actions positively classified as reads.
619 // action_writes() allowlists against THIS rather than negating
620 // write_actions, so an action added to a command later is
621 // refused under a read-only grant until it has been
622 // classified, instead of silently becoming callable.
623 'read_actions' => $read_actions,
624 'handler' => self::cli_handler_for( $command, $spec['synopsis'] ),
625 );
626 }
627 return $tools;
628 }
629
630 /** Derive an MCP tool name from a CLI command ("xspeed cf" -> "xspeed_cf"). */
631 private static function cli_tool_name( string $command ): string {
632 $command = trim( preg_replace( '/\s+/', ' ', $command ) ?? '' );
633 if ( '' === $command ) {
634 return '';
635 }
636 return str_replace( ' ', '_', $command );
637 }
638
639 /** Action verbs that only inspect state (never mutate). */
640 private const CLI_READ_VERBS = array( 'status', 'scan', 'list', 'verify', 'get', 'show', 'info', 'export', 'preview', 'check', 'snippet', 'test' );
641
642 /** Commands with NO action enum that are nonetheless pure inspection. */
643 private const CLI_READ_ONLY_COMMANDS = array( 'xspeed health', 'xspeed support' );
644
645 /**
646 * Compute the write profile for a generated command tool:
647 * [ $write_bool, $write_actions ]
648 * where $write_actions is the list of action values that mutate state
649 * (empty when the tool has no action enum). $write_bool is the tool-level
650 * flag: true if ANY action writes (so read-only clients see it flagged),
651 * but per-action enforcement in invoke() still lets a read-only grant run
652 * the tool's read actions (e.g. `minify status` while `minify purge` is
653 * refused).
654 *
655 * @param string $command Full command name.
656 * @param array $synopsis Command synopsis.
657 * @return array{0:bool,1:string[],2:string[]} write flag, write actions, read actions
658 */
659 /**
660 * Does THIS call mutate state, given the action the caller submitted?
661 *
662 * The tool-level `write` flag is true when ANY of a command's actions
663 * write, so read-only clients can see the tool is capable of mutating.
664 * Enforcing on that flag alone refuses the whole tool — which is how a
665 * read-only grant lost the ability to run `xspeed_minify status` even
666 * though only `purge` writes. `write_actions` records exactly which
667 * action values mutate; this is what reads it.
668 *
669 * Fails CLOSED in every ambiguous case. An action that isn't in the
670 * schema, an absent action, or a tool with no per-action profile all fall
671 * back to the coarse flag and are refused. A read-only grant may end up
672 * with less access than strictly necessary; it must never end up with
673 * more.
674 *
675 * @param array $tool The catalog entry.
676 * @param array $args The submitted arguments.
677 */
678 private static function action_writes( array $tool, array $args ): bool {
679 $write_actions = isset( $tool['write_actions'] ) && is_array( $tool['write_actions'] )
680 ? $tool['write_actions']
681 : array();
682
683 // No per-action profile — the coarse flag is all we have.
684 if ( empty( $write_actions ) ) {
685 return true;
686 }
687
688 $action = isset( $args['action'] ) && is_scalar( $args['action'] )
689 ? strtolower( trim( (string) $args['action'] ) )
690 : '';
691
692 // No action supplied: the command's own default is unknown here, so
693 // treat it as a write rather than guessing.
694 if ( '' === $action ) {
695 return true;
696 }
697
698 // Only an action we positively recognise as read is allowed through.
699 // Anything unknown is refused, so a future action added to a command
700 // can't silently become callable under a read-only grant before it has
701 // been classified.
702 $known = array_map(
703 static function ( $a ) {
704 return strtolower( trim( (string) $a ) );
705 },
706 isset( $tool['read_actions'] ) && is_array( $tool['read_actions'] ) ? $tool['read_actions'] : array()
707 );
708
709 return ! in_array( $action, $known, true );
710 }
711
712 private static function cli_write_profile( string $command, array $synopsis ): array {
713 // Command with an action enum → classify each action.
714 foreach ( $synopsis as $arg ) {
715 if ( isset( $arg['type'], $arg['options'] ) && 'positional' === $arg['type'] && is_array( $arg['options'] ) ) {
716 $write_actions = array();
717 $read_actions = array();
718 foreach ( $arg['options'] as $opt ) {
719 if ( in_array( strtolower( (string) $opt ), self::CLI_READ_VERBS, true ) ) {
720 $read_actions[] = (string) $opt;
721 } else {
722 $write_actions[] = (string) $opt;
723 }
724 }
725 return array( ! empty( $write_actions ), $write_actions, $read_actions );
726 }
727 }
728
729 // No action enum: a small allow-list of pure-inspection commands is
730 // read-only; everything else defaults to write (safe — a read-only
731 // grant never mutates).
732 $is_read = in_array( trim( $command ), self::CLI_READ_ONLY_COMMANDS, true );
733 return array( ! $is_read, array(), array() );
734 }
735
736 /**
737 * Build the handler for a generated command tool. It maps the tool's
738 * arguments back to Cli_Bridge::run(): positional synopsis args (in order)
739 * become $args; everything else is passed as named options.
740 *
741 * @param string $command Full command name.
742 * @param array $synopsis Command synopsis.
743 * @return callable
744 */
745 private static function cli_handler_for( string $command, array $synopsis ): callable {
746 // Names of the positional args, in declared order.
747 $positionals = array();
748 foreach ( $synopsis as $arg ) {
749 if ( isset( $arg['name'] ) && ( ! isset( $arg['type'] ) || 'positional' === $arg['type'] ) ) {
750 $positionals[] = (string) $arg['name'];
751 }
752 }
753
754 return static function ( array $tool_args ) use ( $command, $positionals ) {
755 $args = array();
756 $assoc = $tool_args;
757 // Pull positionals out (in order) into $args; the rest are options.
758 foreach ( $positionals as $pname ) {
759 if ( array_key_exists( $pname, $assoc ) && '' !== (string) $assoc[ $pname ] ) {
760 $args[] = (string) $assoc[ $pname ];
761 }
762 unset( $assoc[ $pname ] );
763 }
764 return Cli_Bridge::run( $command, $args, $assoc );
765 };
766 }
767
768 /**
769 * The tool list in MCP `tools/list` shape.
770 *
771 * @return array<int, array{name:string, description:string, inputSchema:array}>
772 */
773 public static function list(): array {
774 $out = array();
775 foreach ( self::catalog() as $name => $spec ) {
776 $out[] = array(
777 'name' => $name,
778 'description' => $spec['description'],
779 'inputSchema' => $spec['inputSchema'],
780 );
781 }
782 return $out;
783 }
784
785 /**
786 * Invoke a tool by name with decoded arguments.
787 *
788 * @param string $name Tool name.
789 * @param array $args Decoded arguments.
790 * @return array|\WP_Error Result payload or error.
791 */
792 public static function invoke( string $name, array $args ) {
793 $catalog = self::catalog();
794 if ( ! isset( $catalog[ $name ] ) ) {
795 $error = new \WP_Error(
796 'xspeed_mcp_unknown_tool',
797 sprintf(
798 /* translators: %s: tool name. */
799 __( 'Unknown tool: %s', 'xspeed' ),
800 $name
801 ),
802 array( 'status' => 404 )
803 );
804
805 // A call for a tool that doesn't exist is still something that
806 // happened to this site, and a run of them is the shape of a
807 // probe. Recording it is the difference between a trail that
808 // shows what was ATTEMPTED and one that only shows what
809 // succeeded. Scope is unknowable here, so log the conservative
810 // one rather than implying the attempt was read-only.
811 Mcp_Activity_Log::record( $name, $args, false, $error->get_error_message(), 'write', self::$channel );
812
813 return $error;
814 }
815
816 // Scope enforcement: a read-only connection cannot invoke a tool that
817 // mutates state. run_command is a gateway to the full CLI surface, so
818 // it's treated as write regardless of the wrapped command. The active
819 // credential's scope (pairing token OR OAuth access token) is carried
820 // in self::$scope_override; it falls back to the pairing global for
821 // callers that don't set a per-call scope.
822 if ( ! empty( $catalog[ $name ]['write'] ) && self::is_read_only() && self::action_writes( $catalog[ $name ], $args ) ) {
823 return new \WP_Error(
824 'xspeed_mcp_read_only',
825 sprintf(
826 /* translators: %s: tool name. */
827 __( 'This MCP connection is read-only; the "%s" tool changes state and is not permitted. Reconnect with write access to use it.', 'xspeed' ),
828 $name
829 ),
830 array( 'status' => 403 )
831 );
832 }
833
834 self::$dispatching = true;
835 try {
836 $result = call_user_func( $catalog[ $name ]['handler'], $args );
837
838 // Audit every dispatched call — this is the record the admin
839 // reads to answer "what did the assistant do to my site?".
840 // Recorded here (not per-handler) so a new tool is covered the
841 // moment it joins the catalog.
842 [ $ok, $error ] = self::outcome( $result );
843
844 $scope = empty( $catalog[ $name ]['write'] ) ? 'read' : 'write';
845
846 Mcp_Activity_Log::record( $name, $args, $ok, $error, $scope, self::$channel );
847
848 return $result;
849 } finally {
850 self::$dispatching = false;
851 }
852 }
853
854 /**
855 * Read success/failure out of a handler result.
856 *
857 * Two failure shapes reach here. A handler that validates its own
858 * input returns WP_Error. A handler that delegates to Cli_Bridge gets
859 * back an ARRAY carrying `ok => false` plus `error`, because a
860 * `WP_CLI::error()` inside the shim is a controlled failure rather
861 * than an exception. Reading only the first shape logged every failed
862 * command — a refused purge, a Cloudflare call with no credentials —
863 * as a success.
864 *
865 * @param mixed $result Handler return value.
866 * @return array{0:bool,1:string}
867 */
868 private static function outcome( $result ): array {
869 if ( is_wp_error( $result ) ) {
870 return array( false, $result->get_error_message() );
871 }
872
873 if ( is_array( $result ) && array_key_exists( 'ok', $result ) && ! $result['ok'] ) {
874 $error = isset( $result['error'] ) ? (string) $result['error'] : '';
875 return array( false, '' === $error ? 'Command reported failure.' : $error );
876 }
877
878 return array( true, '' );
879 }
880
881 /** @var string Transport that carried the current call (for the audit log). */
882 private static $channel = 'mcp';
883
884 /**
885 * Name the transport for subsequent invokes — the JSON-RPC endpoint and
886 * the hosted-broker REST routes share this catalog, and the audit trail
887 * should say which one a call arrived on.
888 */
889 public static function set_channel( string $channel ): void {
890 self::$channel = '' === $channel ? 'mcp' : $channel;
891 }
892
893 /** @var bool True while an MCP tool handler is executing. */
894 private static $dispatching = false;
895
896 /**
897 * True while a tool call is being dispatched — lets deeper layers
898 * (e.g. the settings change-log) attribute a mutation to MCP.
899 */
900 public static function in_dispatch(): bool {
901 return self::$dispatching;
902 }
903
904 /*
905 * Handlers — thin proxies to the Free engine. Each takes decoded tool
906 * arguments and returns an array payload (or WP_Error on bad input).
907 */
908
909 /**
910 * Cache status, stats, and detected server.
911 *
912 * @param array $args Unused.
913 * @return array
914 */
915 public static function get_cache_status( array $args ) {
916 unset( $args );
917 $opts = Settings::get();
918 return array(
919 'cache_enabled' => (bool) ( $opts['cache_enabled'] ?? false ),
920 'stats' => Cache::get_stats(),
921 'server' => Server::type(),
922 );
923 }
924
925 /**
926 * All registered module descriptors.
927 *
928 * @param array $args Unused.
929 * @return array
930 */
931 public static function list_modules( array $args ) {
932 unset( $args );
933 return Admin::modules_payload();
934 }
935
936 /**
937 * Before/after cache benchmark timings.
938 *
939 * @param array $args Unused.
940 * @return array
941 */
942 public static function run_benchmark( array $args ) {
943 unset( $args );
944 return Cache_Benchmark::run();
945 }
946
947 /**
948 * Personalized Pro-feature suggestions for this site.
949 *
950 * @param array $args Unused.
951 * @return array
952 */
953 public static function get_pro_audit( array $args ) {
954 unset( $args );
955 return array( 'suggestions' => Pro_Audit::run() );
956 }
957
958 /**
959 * Purge the cache by type.
960 *
961 * @param array $args { type?:string } — one of PURGE_TYPES; default all.
962 * @return array|\WP_Error
963 */
964 public static function purge_cache( array $args ) {
965 $type = isset( $args['type'] ) ? (string) $args['type'] : 'all';
966 if ( '' === $type ) {
967 $type = 'all';
968 }
969 if ( ! in_array( $type, self::PURGE_TYPES, true ) ) {
970 return new \WP_Error(
971 'xspeed_mcp_bad_type',
972 sprintf(
973 /* translators: %s: comma-separated list of valid purge types. */
974 __( 'Invalid purge type. Expected one of: %s', 'xspeed' ),
975 implode( ', ', self::PURGE_TYPES )
976 ),
977 array( 'status' => 400 )
978 );
979 }
980 // Named source, not the default "manual": the purge log's whole job
981 // is to let an admin see that the cache cleared because an assistant
982 // asked, not because someone clicked.
983 $count = Cache::purge_type( $type, __( 'AI assistant', 'xspeed' ) );
984 return array(
985 'purged' => $type,
986 'count' => $count,
987 'stats' => Cache::get_stats(),
988 );
989 }
990
991 /**
992 * Enable or disable page caching.
993 *
994 * @param array $args { enabled:bool }.
995 * @return array|\WP_Error
996 */
997 public static function toggle_cache( array $args ) {
998 if ( ! array_key_exists( 'enabled', $args ) ) {
999 return new \WP_Error(
1000 'xspeed_mcp_missing_enabled',
1001 __( 'The "enabled" parameter is required (true or false).', 'xspeed' ),
1002 array( 'status' => 400 )
1003 );
1004 }
1005 $enabled = rest_sanitize_boolean( $args['enabled'] );
1006 $install = Cache::toggle( $enabled );
1007
1008 // Persist cache_enabled the same way the Free /cache/toggle route
1009 // does (class-rest-api.php:235) — Cache::toggle handles the drop-in
1010 // + wp-config; Settings owns the option flag.
1011 Settings::update( array( 'cache_enabled' => $enabled ) );
1012
1013 return array(
1014 'cache_enabled' => $enabled,
1015 'install_state' => $install,
1016 'stats' => Cache::get_stats(),
1017 );
1018 }
1019
1020 /**
1021 * Read a module's schema-validated settings.
1022 *
1023 * @param array $args { module:string }.
1024 * @return array|\WP_Error
1025 */
1026 public static function get_settings( array $args ) {
1027 $module = isset( $args['module'] ) ? (string) $args['module'] : '';
1028 if ( '' === $module ) {
1029 return new \WP_Error(
1030 'xspeed_mcp_missing_module',
1031 __( 'The "module" parameter is required.', 'xspeed' ),
1032 array( 'status' => 400 )
1033 );
1034 }
1035 return array(
1036 'module' => $module,
1037 // Public view — secret fields masked. An MCP agent must never be able
1038 // to read stored credentials back in plaintext. (#115)
1039 'settings' => Settings_Manager::get_public( $module ),
1040 );
1041 }
1042
1043 /**
1044 * Update a module's settings (schema-validated).
1045 *
1046 * @param array $args { module:string, values:array }.
1047 * @return array|\WP_Error
1048 */
1049 public static function update_settings( array $args ) {
1050 $module = isset( $args['module'] ) ? (string) $args['module'] : '';
1051 $values = $args['values'] ?? null;
1052 if ( '' === $module ) {
1053 return new \WP_Error(
1054 'xspeed_mcp_missing_module',
1055 __( 'The "module" parameter is required.', 'xspeed' ),
1056 array( 'status' => 400 )
1057 );
1058 }
1059 if ( ! is_array( $values ) ) {
1060 return new \WP_Error(
1061 'xspeed_mcp_bad_values',
1062 __( 'The "values" parameter must be an object of setting keys.', 'xspeed' ),
1063 array( 'status' => 400 )
1064 );
1065 }
1066 // Writing credentials over MCP requires the explicit `configure` grant —
1067 // off by default even for a write-scoped connection — so an agent can't
1068 // silently repoint the Cloudflare/object-cache backend at an attacker
1069 // endpoint. Refuse with a message naming exactly which fields need it.
1070 // (Settings_Manager::update also strips these as a backstop covering the
1071 // run_command → CLI path.) (#116)
1072 if ( ! self::can_configure() ) {
1073 $secret_fields = Settings_Manager::secret_keys_in( $module, $values );
1074 if ( ! empty( $secret_fields ) ) {
1075 return new \WP_Error(
1076 'xspeed_mcp_configure_required',
1077 sprintf(
1078 /* translators: 1: comma-separated field names, 2: module slug. */
1079 __( 'Writing credential fields (%1$s) on "%2$s" needs the "configure" scope, which is off by default. Reconnect the MCP client granting the configure scope, or set these credentials from the xSpeed dashboard.', 'xspeed' ),
1080 implode( ', ', $secret_fields ),
1081 $module
1082 ),
1083 array(
1084 'status' => 403,
1085 'refused_fields' => $secret_fields,
1086 )
1087 );
1088 }
1089 }
1090 return array(
1091 'module' => $module,
1092 // Return value is already masked (Settings_Manager::update returns the
1093 // public view), so a written secret isn't echoed back either. (#115)
1094 'settings' => Settings_Manager::update( $module, $values ),
1095 );
1096 }
1097
1098 /**
1099 * List every command run_command can invoke (the full CLI surface).
1100 *
1101 * @param array $args Unused.
1102 * @return array
1103 */
1104 public static function list_commands( array $args ) {
1105 unset( $args );
1106 return array( 'commands' => Cli_Bridge::catalog() );
1107 }
1108
1109 /**
1110 * Run any registered xSpeed command via the CLI bridge.
1111 *
1112 * @param array $args { command:string, args?:array, options?:array }.
1113 * @return array|\WP_Error
1114 */
1115 public static function run_command( array $args ) {
1116 $command = isset( $args['command'] ) ? (string) $args['command'] : '';
1117 if ( '' === $command ) {
1118 return new \WP_Error(
1119 'xspeed_mcp_missing_command',
1120 __( 'The "command" parameter is required.', 'xspeed' ),
1121 array( 'status' => 400 )
1122 );
1123 }
1124 $positional = isset( $args['args'] ) && is_array( $args['args'] ) ? $args['args'] : array();
1125 $options = isset( $args['options'] ) && is_array( $args['options'] ) ? $args['options'] : array();
1126 return Cli_Bridge::run( $command, $positional, $options );
1127 }
1128
1129 /* --------------------------------------------------------------------- */
1130 /* Promoted action handlers — typed wrappers over Cli_Bridge. */
1131 /* Delegating to the bridge lets a Free tool drive a Pro action (psi, */
1132 /* ccss) with no cross-repo class reference, and keeps zero drift. */
1133 /* --------------------------------------------------------------------- */
1134
1135 /**
1136 * Purge the Cloudflare edge cache.
1137 *
1138 * @param array $args Unused.
1139 * @return array|\WP_Error
1140 */
1141 public static function purge_cloudflare( array $args ) {
1142 unset( $args );
1143 return Cli_Bridge::run( 'cf', array( 'purge' ) );
1144 }
1145
1146 /**
1147 * Scan the database for bloat (no deletion).
1148 *
1149 * @param array $args Unused.
1150 * @return array|\WP_Error
1151 */
1152 public static function scan_database( array $args ) {
1153 unset( $args );
1154 return Cli_Bridge::run( 'db', array( 'scan' ) );
1155 }
1156
1157 /**
1158 * Clean database bloat (destructive).
1159 *
1160 * @param array $args Unused.
1161 * @return array|\WP_Error
1162 */
1163 public static function clean_database( array $args ) {
1164 unset( $args );
1165 return Cli_Bridge::run( 'db', array( 'clean' ) );
1166 }
1167
1168 /**
1169 * Flush the persistent object cache.
1170 *
1171 * @param array $args Unused.
1172 * @return array|\WP_Error
1173 */
1174 public static function flush_object_cache( array $args ) {
1175 unset( $args );
1176 return Cli_Bridge::run( 'objcache', array( 'flush' ) );
1177 }
1178
1179 /**
1180 * Start the cache preloader.
1181 *
1182 * @param array $args Unused.
1183 * @return array|\WP_Error
1184 */
1185 public static function start_preloader( array $args ) {
1186 unset( $args );
1187 return Cli_Bridge::run( 'preloader', array( 'start' ) );
1188 }
1189
1190 /**
1191 * Full health diagnostics (checks + stats + buckets + activity).
1192 * Direct typed payload — same tier as get_cache_status — so the agent
1193 * gets structured tones/ids instead of parsing CLI log lines.
1194 *
1195 * @param array $args Unused.
1196 * @return array
1197 */
1198 public static function get_health( array $args ) {
1199 unset( $args );
1200 return array(
1201 'checks' => \XSpeed\Health::checks(),
1202 'stats' => Cache::get_stats(),
1203 'buckets' => \XSpeed\Hit_Counter::buckets(),
1204 'hit_daily' => \XSpeed\Hit_Counter::daily_series( 30 ),
1205 'activity' => \XSpeed\Activity_Log::entries(),
1206 );
1207 }
1208
1209 /**
1210 * Stored benchmark runs + settings-change events (trend data).
1211 *
1212 * @param array $args { limit?:int }.
1213 * @return array
1214 */
1215 public static function get_benchmark_history( array $args ) {
1216 $limit = isset( $args['limit'] ) ? max( 1, min( 100, (int) $args['limit'] ) ) : 100;
1217 $changes = array();
1218 foreach ( \XSpeed\Activity_Log::entries() as $entry ) {
1219 if ( 'settings_changed' === ( $entry['type'] ?? '' ) ) {
1220 $changes[] = array(
1221 'ts' => (int) $entry['ts'],
1222 'message' => (string) $entry['message'],
1223 );
1224 }
1225 }
1226 return array(
1227 'runs' => Cache_Benchmark::history( $limit ),
1228 'changes' => $changes,
1229 );
1230 }
1231
1232 /**
1233 * Purge a single URL's cache entries.
1234 *
1235 * @param array $args { url:string }.
1236 * @return array|\WP_Error
1237 */
1238 /**
1239 * Inspect what is in the page cache (pages + age, or size breakdown).
1240 *
1241 * @param array $args detail: pages|size, limit.
1242 * @return array|\WP_Error
1243 */
1244 public static function get_cache_inventory( array $args ) {
1245 $detail = isset( $args['detail'] ) ? (string) $args['detail'] : 'pages';
1246 $action = 'size' === $detail ? 'size' : 'inventory';
1247 $assoc = array();
1248 if ( isset( $args['limit'] ) && '' !== $args['limit'] ) {
1249 $assoc['limit'] = (string) $args['limit'];
1250 }
1251 return Cli_Bridge::run( 'cache', array( $action ), $assoc );
1252 }
1253
1254 /**
1255 * Recent cache purges and their causes.
1256 *
1257 * @param array $args limit.
1258 * @return array|\WP_Error
1259 */
1260 public static function get_purge_log( array $args ) {
1261 $assoc = array();
1262 if ( isset( $args['limit'] ) && '' !== $args['limit'] ) {
1263 $assoc['limit'] = (string) $args['limit'];
1264 }
1265 return Cli_Bridge::run( 'cache', array( 'purge-log' ), $assoc );
1266 }
1267
1268 /**
1269 * Re-verify (and repair) the server rewrite rules.
1270 *
1271 * @param array $args Unused.
1272 * @return array|\WP_Error
1273 */
1274 public static function recheck_rewrite_rules( array $args ) {
1275 unset( $args );
1276 return Cli_Bridge::run( 'cache', array( 'recheck-rewrite' ) );
1277 }
1278
1279 /**
1280 * Turn Cloudflare development mode on or off.
1281 *
1282 * A boolean rather than two tools: dev-on and dev-off are one decision,
1283 * and offering them separately doubles the surface for no gain.
1284 *
1285 * @param array $args enabled (bool, required).
1286 * @return array|\WP_Error
1287 */
1288 public static function set_cloudflare_dev_mode( array $args ) {
1289 if ( ! array_key_exists( 'enabled', $args ) ) {
1290 return new \WP_Error( 'xspeed_mcp_missing_enabled', __( 'The enabled argument is required.', 'xspeed' ), array( 'status' => 400 ) );
1291 }
1292 $on = filter_var( $args['enabled'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE );
1293 if ( null === $on ) {
1294 return new \WP_Error( 'xspeed_mcp_invalid_enabled', __( 'The enabled argument must be true or false.', 'xspeed' ), array( 'status' => 400 ) );
1295 }
1296 return Cli_Bridge::run( 'cf', array( $on ? 'dev-on' : 'dev-off' ) );
1297 }
1298
1299 /**
1300 * Optimize database tables (distinct from clean_database, which deletes).
1301 *
1302 * @param array $args Unused.
1303 * @return array|\WP_Error
1304 */
1305 public static function optimize_database( array $args ) {
1306 unset( $args );
1307 return Cli_Bridge::run( 'db', array( 'optimize' ) );
1308 }
1309
1310 /**
1311 * Object cache state, or the server snippet that enables it.
1312 *
1313 * @param array $args detail: status|snippet.
1314 * @return array|\WP_Error
1315 */
1316 public static function get_object_cache_status( array $args ) {
1317 $detail = isset( $args['detail'] ) ? (string) $args['detail'] : 'status';
1318 $action = 'snippet' === $detail ? 'snippet' : 'status';
1319 return Cli_Bridge::run( 'objcache', array( $action ) );
1320 }
1321
1322 /**
1323 * Install or remove the object-cache drop-in.
1324 *
1325 * @param array $args enabled (bool, required).
1326 * @return array|\WP_Error
1327 */
1328 public static function toggle_object_cache( array $args ) {
1329 if ( ! array_key_exists( 'enabled', $args ) ) {
1330 return new \WP_Error( 'xspeed_mcp_missing_enabled', __( 'The enabled argument is required.', 'xspeed' ), array( 'status' => 400 ) );
1331 }
1332 $on = filter_var( $args['enabled'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE );
1333 if ( null === $on ) {
1334 return new \WP_Error( 'xspeed_mcp_invalid_enabled', __( 'The enabled argument must be true or false.', 'xspeed' ), array( 'status' => 400 ) );
1335 }
1336 return Cli_Bridge::run( 'objcache', array( $on ? 'enable' : 'disable' ) );
1337 }
1338
1339 /**
1340 * List or clear stored Critical CSS.
1341 *
1342 * @param array $args action: list|clear.
1343 * @return array|\WP_Error
1344 */
1345 public static function manage_critical_css( array $args ) {
1346 $action = isset( $args['action'] ) ? (string) $args['action'] : '';
1347 if ( ! in_array( $action, array( 'list', 'clear' ), true ) ) {
1348 return new \WP_Error( 'xspeed_mcp_invalid_action', __( 'The action argument must be "list" or "clear".', 'xspeed' ), array( 'status' => 400 ) );
1349 }
1350 return Cli_Bridge::run( 'ccss', array( $action ) );
1351 }
1352
1353 /**
1354 * Preloader progress.
1355 *
1356 * @param array $args Unused.
1357 * @return array|\WP_Error
1358 */
1359 public static function get_preloader_status( array $args ) {
1360 unset( $args );
1361 return Cli_Bridge::run( 'preloader', array( 'status' ) );
1362 }
1363
1364 /**
1365 * Stop a running preload.
1366 *
1367 * @param array $args Unused.
1368 * @return array|\WP_Error
1369 */
1370 public static function stop_preloader( array $args ) {
1371 unset( $args );
1372 return Cli_Bridge::run( 'preloader', array( 'stop' ) );
1373 }
1374
1375 /**
1376 * Stored external audit runs (PSI / GTmetrix).
1377 *
1378 * Read-only by construction: it reads the option Score already wrote. No
1379 * outbound call is made, which is what lets the Hub poll this on a
1380 * schedule without spending the site owner's PSI or GTmetrix quota.
1381 *
1382 * @param array $args limit.
1383 * @return array|\WP_Error
1384 */
1385 public static function get_score_history( array $args ) {
1386 if ( ! class_exists( '\\XSpeed\\Score' ) ) {
1387 return new \WP_Error( 'xspeed_mcp_no_score', __( 'External scores are not available on this site.', 'xspeed' ), array( 'status' => 404 ) );
1388 }
1389
1390 $limit = isset( $args['limit'] ) ? (int) $args['limit'] : 100;
1391 $limit = max( 1, min( 500, $limit ) );
1392
1393 $runs = array();
1394 foreach ( array_slice( \XSpeed\Score::history(), 0, $limit ) as $run ) {
1395 if ( ! is_array( $run ) ) {
1396 continue;
1397 }
1398 $metrics = isset( $run['metrics'] ) && is_array( $run['metrics'] ) ? $run['metrics'] : array();
1399 $runs[] = array(
1400 'provider' => isset( $run['provider'] ) ? (string) $run['provider'] : 'unknown',
1401 'ts' => isset( $run['ts'] ) ? (int) $run['ts'] : 0,
1402 'url' => isset( $run['url'] ) ? (string) $run['url'] : '',
1403 'strategy' => isset( $run['strategy'] ) ? (string) $run['strategy'] : null,
1404 // Null, never 0: Score distinguishes "no score" from "scored
1405 // zero", and flattening that reports a failed audit as a
1406 // catastrophic result.
1407 'score' => isset( $run['score'] ) && is_numeric( $run['score'] ) ? (int) $run['score'] : null,
1408 'metrics' => array(
1409 'lcp' => self::metric_or_null( $metrics, 'lcp' ),
1410 'fcp' => self::metric_or_null( $metrics, 'fcp' ),
1411 'cls' => self::metric_or_null( $metrics, 'cls' ),
1412 'tbt' => self::metric_or_null( $metrics, 'tbt' ),
1413 'si' => self::metric_or_null( $metrics, 'si' ),
1414 'ttfb' => self::metric_or_null( $metrics, 'ttfb' ),
1415 ),
1416 'report_url' => self::report_url_for( $run ),
1417 );
1418 }
1419
1420 return array(
1421 'runs' => $runs,
1422 'total' => count( \XSpeed\Score::history() ),
1423 );
1424 }
1425
1426 /**
1427 * One metric as a float, or null when absent/non-numeric.
1428 *
1429 * @param array $metrics Metric bag.
1430 * @param string $key Metric id.
1431 */
1432 private static function metric_or_null( array $metrics, string $key ): ?float {
1433 return isset( $metrics[ $key ] ) && is_numeric( $metrics[ $key ] ) ? (float) $metrics[ $key ] : null;
1434 }
1435
1436 /**
1437 * Deep link to the provider's own report, when one exists.
1438 *
1439 * GTmetrix hosts a durable report per test, so its id is enough to build
1440 * the link. PSI does NOT — a Lighthouse result is returned to the caller
1441 * and never hosted, so there is genuinely nothing to link to and this
1442 * returns null rather than inventing a URL that 404s.
1443 *
1444 * @param array $run One stored run.
1445 */
1446 private static function report_url_for( array $run ): ?string {
1447 $provider = isset( $run['provider'] ) ? (string) $run['provider'] : '';
1448 if ( 'gtmetrix' !== $provider ) {
1449 return null;
1450 }
1451 $test_id = isset( $run['test_id'] ) ? trim( (string) $run['test_id'] ) : '';
1452 if ( '' === $test_id ) {
1453 return null;
1454 }
1455 return 'https://gtmetrix.com/reports/' . rawurlencode( $test_id );
1456 }
1457
1458 public static function purge_url( array $args ) {
1459 $url = isset( $args['url'] ) ? trim( (string) $args['url'] ) : '';
1460 if ( '' === $url ) {
1461 return new \WP_Error( 'xspeed_mcp_missing_url', __( 'The url argument is required.', 'xspeed' ), array( 'status' => 400 ) );
1462 }
1463 return Cli_Bridge::run( 'cache', array( 'purge-url', $url ), array( 'cause' => __( 'AI assistant', 'xspeed' ) ) );
1464 }
1465
1466 /**
1467 * Probe the configured object-cache backend (connect + read/write).
1468 *
1469 * @param array $args Unused.
1470 * @return array|\WP_Error
1471 */
1472 public static function test_object_cache( array $args ) {
1473 unset( $args );
1474 return Cli_Bridge::run( 'objcache', array( 'test' ) );
1475 }
1476
1477 /**
1478 * Verify the saved Cloudflare credentials.
1479 *
1480 * @param array $args Unused.
1481 * @return array|\WP_Error
1482 */
1483 public static function cloudflare_verify( array $args ) {
1484 unset( $args );
1485 return Cli_Bridge::run( 'cf', array( 'verify' ) );
1486 }
1487
1488 /**
1489 * Run a PageSpeed Insights audit (Pro).
1490 *
1491 * @param array $args { url?:string, strategy?:string }.
1492 * @return array|\WP_Error
1493 */
1494 public static function run_pagespeed( array $args ) {
1495 $options = array();
1496 if ( ! empty( $args['url'] ) ) {
1497 $options['url'] = (string) $args['url'];
1498 }
1499 if ( ! empty( $args['strategy'] ) ) {
1500 $options['strategy'] = (string) $args['strategy'];
1501 }
1502 // Was reachable only via the generated xspeed_psi alias, which this
1503 // change removes — so it moves onto the typed tool rather than being
1504 // lost with it.
1505 if ( ! empty( $args['force'] ) && filter_var( $args['force'], FILTER_VALIDATE_BOOLEAN ) ) {
1506 $options['force'] = true;
1507 }
1508
1509 // Prefer the richer Pro engine when it's installed; otherwise drive
1510 // Free's own score command. Same tool name either way — an assistant
1511 // asking for a PageSpeed audit shouldn't have to know which tier the
1512 // site runs, and the two write to the same run history.
1513 if ( isset( Cli_Bridge::commands()['xspeed psi'] ) ) {
1514 return Cli_Bridge::run( 'psi', array(), $options );
1515 }
1516 return Cli_Bridge::run( 'score', array( 'run' ), $options );
1517 }
1518
1519 /**
1520 * Generate Critical CSS (Pro).
1521 *
1522 * @param array $args Unused.
1523 * @return array|\WP_Error
1524 */
1525 public static function generate_critical_css( array $args ) {
1526 unset( $args );
1527 return Cli_Bridge::run( 'ccss', array( 'generate' ) );
1528 }
1529
1530 /**
1531 * Build a JSON Schema object node.
1532 *
1533 * @param array $properties Property map.
1534 * @param string[] $required Required property names.
1535 */
1536 private static function object_schema( array $properties, array $required ): array {
1537 $schema = array(
1538 'type' => 'object',
1539 'properties' => (object) $properties,
1540 );
1541 if ( ! empty( $required ) ) {
1542 $schema['required'] = array_values( $required );
1543 }
1544 return $schema;
1545 }
1546 }
1547