PluginProbe
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN / 1.3.3
xSpeed Cache: AI-Powered Performance Hub with MCP, Caching & CDN v1.3.3
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
← All changes | includes/modules/Mcp/McpModule.php +287 -21 1.1.31.3.3 View file →
@@ -47,11 +47,40 @@
47 47 public const SLUG = 'mcp';
48 48 public const TIER = self::TIER_FREE;
49 49 public const VERSION = '1.0.0';
50 50
51 - /** REST namespace shared with Free. */
52 - private const NS = 'xspeed/v1';
51 + /**
52 + * Every rewrite rule this module registers, in registration order.
53 + *
54 + * Single source of truth: add_rewrite() registers these, and the self-heal
55 + * guard re-flushes when any is missing from the stored table. They were two
56 + * hand-maintained lists before, which is a silent drift risk — a rule
57 + * dropped from one and not the other leaves the guard restoring a rule
58 + * nothing registers, or never firing for one that is registered.
59 + *
60 + * @var string[] Rewrite regexes. The query each maps to is built in
61 + * add_rewrite(), which also fixes their order.
62 + */
63 + public const REWRITE_RULES = array(
64 + '^xspeed/mcp/([a-f0-9]{64})/?$',
65 + '^xspeed/mcp/?$',
66 + '^xspeed/mcp/attach/?$',
67 + // OAuth discovery, root form. RFC 9728 §3.1 / RFC 8414 §3.1 put the
68 + // `.well-known` segment BEFORE the resource path.
69 + '^\.well-known/oauth-(protected-resource|authorization-server)/?$',
70 + // OAuth discovery, path-suffixed form. Real clients (Claude Desktop
71 + // among them) request THIS one; serving only the root form 404s them.
72 + // It names our own resource path explicitly: a catch-all tail here
73 + // also matched other MCP plugins' discovery URLs on the same site and
74 + // answered them with our metadata, which broke their connectors.
75 + '^\.well-known/oauth-(protected-resource|authorization-server)/xspeed/mcp/?$',
76 + '^xspeed/authorize/?$',
77 + );
53 78
79 + /** REST namespace shared with Free. Public: Mcp_Server builds the
80 + * discovery fallback URL from it. */
81 + public const NS = 'xspeed/v1';
82 +
54 83 /** Query var flagging a pretty /xspeed/mcp request. */
55 84 private const QUERY_VAR = 'xspeed_mcp';
56 85
57 86 /** Query var carrying the token when embedded in the URL path. */
@@ -78,11 +107,11 @@
78 107 private const ATTACH_QUERY_VAR = 'xspeed_mcp_attach';
79 108
80 109 public function ui_metadata(): array {
81 110 return array(
82 - 'label' => 'MCP Server',
111 + 'label' => __( 'MCP Server', 'xspeed' ),
83 112 'icon' => 'Sparkles',
84 - 'description' => 'Control this site\'s cache from Claude and other AI agents.',
113 + 'description' => __( 'Control this site\'s cache from Claude and other AI agents.', 'xspeed' ),
85 114 'custom_panel' => 'McpPanel',
86 115 );
87 116 }
88 117
@@ -108,9 +137,13 @@
108 137
109 138 // Pretty per-site endpoint: /xspeed/mcp → MCP JSON-RPC handler.
110 139 add_action( 'init', array( $this, 'add_rewrite' ) );
111 140 add_filter( 'query_vars', array( $this, 'register_query_var' ) );
112 - add_action( 'parse_request', array( $this, 'maybe_handle_pretty_endpoint' ) );
141 + // Priority 1: a sibling MCP plugin that also claims /.well-known/ gets
142 + // to answer first at the default priority 10, and whoever answers
143 + // first calls exit(). Running early means the URL is decided by WHOSE
144 + // path it is, not by which plugin happened to load last.
145 + add_action( 'parse_request', array( $this, 'maybe_handle_pretty_endpoint' ), 1 );
113 146
114 147 // Hub redirect-return: after the user approves on the Hub, it sends the
115 148 // browser back to a plugin admin URL carrying ?xspeed_connected=1 plus
116 149 // the account email + the SAME signed nonce we minted. We verify our own
@@ -116,8 +149,18 @@
116 149 // the account email + the SAME signed nonce we minted. We verify our own
117 150 // nonce and mark this admin attached — no server-to-server callback
118 151 // needed, so it works for local/firewalled sites too.
119 152 add_action( 'admin_init', array( $this, 'maybe_handle_hub_return' ) );
153 +
154 + // An attached admin who is DELETED (or removed from the blog) never
155 + // runs disconnect(), so the site-level attached mirror would report
156 + // hub:true forever. deleted_user fires after both wp_delete_user()
157 + // and wpmu_delete_user() drop the user, so a plain recompute is
158 + // honest there. remove_user_from_blog is core's only removal action
159 + // and fires BEFORE removal, so its handler clears the departing
160 + // user's record before recomputing (see Mcp_Hub::handle_user_removed).
161 + add_action( 'deleted_user', array( Mcp_Hub::class, 'refresh_site_attached' ) );
162 + add_action( 'remove_user_from_blog', array( Mcp_Hub::class, 'handle_user_removed' ) );
120 163 }
121 164
122 165 /**
123 166 * Handle the browser landing back from the Hub after a connect. Idempotent
@@ -214,21 +257,32 @@
214 257 // (that rule requires 64 hex chars), so ordering is safe.
215 258 add_rewrite_rule( '^xspeed/mcp/attach/?$', 'index.php?' . self::ATTACH_QUERY_VAR . '=1', 'top' );
216 259
217 260 // OAuth discovery documents. RFC 9728 §3.1 / RFC 8414 §3.1 place the
218 - // `.well-known` segment BEFORE the resource path, so a resource at
261 + // `.well-known` segment BEFORE the resource path, so our resource at
219 262 // /xspeed/mcp is discovered at BOTH:
220 263 // /.well-known/oauth-protected-resource (root form)
221 264 // /.well-known/oauth-protected-resource/xspeed/mcp (path-suffixed)
222 - // Real clients (e.g. Claude Desktop) request the path-suffixed form;
223 - // serving only the root form 404s them and the connection aborts. The
224 - // optional `(?:/.*)?` tail matches both without caring about the exact
225 - // resource path (we only serve one resource).
265 + // Real clients (Claude Desktop among them) request the path-suffixed
266 + // form; serving only the root form 404s them and the connection aborts.
267 + //
268 + // Both are matched EXACTLY. A `(?:/.*)?` tail covers the same two URLs
269 + // in one rule, but also matches every OTHER plugin's discovery URL on
270 + // the same site — and WordPress matches rewrite rules in table order
271 + // rather than by specificity, so a sibling's own exact rule never gets
272 + // reached. Its clients then receive OUR metadata, find a resource and
273 + // issuer that do not match what they are connecting to, and abort
274 + // before the login screen.
226 275 add_rewrite_rule(
227 - '^\.well-known/oauth-(protected-resource|authorization-server)(?:/.*)?/?$',
276 + '^\\.well-known/oauth-(protected-resource|authorization-server)/?$',
228 277 'index.php?' . self::WELLKNOWN_QUERY_VAR . '=$matches[1]',
229 278 'top'
230 279 );
280 + add_rewrite_rule(
281 + '^\\.well-known/oauth-(protected-resource|authorization-server)/xspeed/mcp/?$',
282 + 'index.php?' . self::WELLKNOWN_QUERY_VAR . '=$matches[1]',
283 + 'top'
284 + );
231 285
232 286 // Browser-facing OAuth consent page — served OUTSIDE REST so cookie
233 287 // auth (is_user_logged_in) works after the wp-login round-trip.
234 288 add_rewrite_rule( '^xspeed/authorize/?$', 'index.php?' . self::AUTHORIZE_QUERY_VAR . '=1', 'top' );
@@ -238,18 +292,11 @@
238 292 // flushed under an older build (which had /xspeed/mcp but not the
239 293 // later /xspeed/authorize + /.well-known rules) keeps that first rule,
240 294 // so the guard never fires and OAuth discovery 404s forever. Guard on
241 295 // the full set so any newly-added rule triggers a re-flush.
242 - $expected = array(
243 - '^xspeed/mcp/([a-f0-9]{64})/?$',
244 - '^xspeed/mcp/?$',
245 - '^xspeed/mcp/attach/?$',
246 - '^\.well-known/oauth-(protected-resource|authorization-server)(?:/.*)?/?$',
247 - '^xspeed/authorize/?$',
248 - );
249 296 $rules = get_option( 'rewrite_rules' );
250 297 if ( is_array( $rules ) ) {
251 - foreach ( $expected as $rule ) {
298 + foreach ( self::REWRITE_RULES as $rule ) {
252 299 if ( ! isset( $rules[ $rule ] ) ) {
253 300 flush_rewrite_rules( false );
254 301 break;
255 302 }
@@ -257,8 +304,41 @@
257 304 }
258 305 }
259 306
260 307 /**
308 + * True when a request for our discovery URL can reach WordPress at all.
309 + *
310 + * Since maybe_handle_pretty_endpoint() claims the document by REQUEST
311 + * PATH, a sibling plugin winning the rewrite match no longer matters —
312 + * we answer either way. What still breaks the pretty URL is there being
313 + * no rewrite for it in the first place (plain permalinks), because then
314 + * nothing routes the path to index.php and parse_request never runs.
315 + *
316 + * Blind to upstream interception: a host that owns the /.well-known/
317 + * prefix (an nginx ACME block, an edge redirect rule) answers before
318 + * WordPress loads, and WP cannot see that. Use the
319 + * `xspeed_mcp_resource_metadata_url` filter on such hosts.
320 + */
321 + public static function wellknown_rewrites_active(): bool {
322 + $rules = get_option( 'rewrite_rules' );
323 + if ( ! is_array( $rules ) || array() === $rules ) {
324 + return false;
325 + }
326 +
327 + // Any rule that routes our discovery path to index.php will do — ours
328 + // or a sibling's — because the path check inside the handler decides
329 + // the outcome once the request lands.
330 + $probe = '.well-known/oauth-protected-resource';
331 + foreach ( $rules as $pattern => $target ) {
332 + if ( preg_match( '#' . str_replace( '#', '\\#', $pattern ) . '#', $probe ) ) {
333 + return true;
334 + }
335 + }
336 +
337 + return false;
338 + }
339 +
340 + /**
261 341 * @param string[] $vars Registered query vars.
262 342 * @return string[]
263 343 */
264 344 public function register_query_var( array $vars ): array {
@@ -270,8 +350,45 @@
270 350 return $vars;
271 351 }
272 352
273 353 /**
354 + * Which discovery document the CURRENT request path asks for, if any.
355 + *
356 + * Claims only URLs that are unambiguously ours, mirroring the rewrite
357 + * rules exactly: the bare root form, and the RFC 9728 §3.1 path-suffixed
358 + * form naming our own resource (`/xspeed/mcp`). A suffix belonging to a
359 + * sibling plugin is deliberately NOT claimed — answering
360 + * `/.well-known/oauth-protected-resource/betterlinks/mcp` with xSpeed
361 + * metadata is the same bug that broke this site, just pointed the other
362 + * way.
363 + *
364 + * @return string 'protected-resource', 'authorization-server', or ''.
365 + */
366 + private function wellknown_doc_from_path(): string {
367 + $uri = isset( $_SERVER['REQUEST_URI'] )
368 + ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) )
369 + : '';
370 + if ( '' === $uri ) {
371 + return '';
372 + }
373 +
374 + $path = (string) wp_parse_url( $uri, PHP_URL_PATH );
375 +
376 + // Sites in a subdirectory carry that prefix on every request.
377 + $home = (string) wp_parse_url( home_url(), PHP_URL_PATH );
378 + if ( '' !== $home && '/' !== $home && 0 === strpos( $path, $home ) ) {
379 + $path = substr( $path, strlen( $home ) );
380 + }
381 +
382 + $path = trim( $path, '/' );
383 +
384 + $pattern = '#^\.well-known/oauth-(protected-resource|authorization-server)'
385 + . '(?:/xspeed/mcp)?$#';
386 +
387 + return preg_match( $pattern, $path, $m ) ? $m[1] : '';
388 + }
389 +
390 + /**
274 391 * Serve the MCP endpoint on the pretty path. Runs on parse_request so
275 392 * it fires before the main query, and short-circuits WP entirely.
276 393 *
277 394 * @param \WP $wp The WP request object.
@@ -277,10 +394,24 @@
277 394 * @param \WP $wp The WP request object.
278 395 */
279 396 public function maybe_handle_pretty_endpoint( $wp ): void {
280 397 // OAuth discovery documents (served at the site root).
281 - if ( ! empty( $wp->query_vars[ self::WELLKNOWN_QUERY_VAR ] ) ) {
398 + //
399 + // Read the doc name from the REQUEST PATH, not just our query var.
400 + // `add_rewrite_rule( …, 'top' )` only means "top at the moment it
401 + // runs", so whichever MCP plugin hooks `init` last ends up first in
402 + // the table — an order set by plugin load order, which no plugin
403 + // controls. A sibling's catch-all
404 + // (`…(protected-resource|authorization-server)(?:/.*)?/?$`) then wins
405 + // the match and our query var is never set, even though the URL is
406 + // unambiguously ours. Observed live with two different plugins on one
407 + // site. parse_request runs AFTER matching, so the path is the one
408 + // signal no sibling rule can take away from us.
409 + $doc = $this->wellknown_doc_from_path();
410 + if ( '' === $doc && ! empty( $wp->query_vars[ self::WELLKNOWN_QUERY_VAR ] ) ) {
282 411 $doc = (string) $wp->query_vars[ self::WELLKNOWN_QUERY_VAR ];
412 + }
413 + if ( '' !== $doc ) {
283 414 $data = 'authorization-server' === $doc
284 415 ? Mcp_OAuth::authorization_server_metadata()
285 416 : Mcp_OAuth::protected_resource_metadata();
286 417 status_header( 200 );
@@ -360,8 +491,26 @@
360 491 'permission_callback' => '__return_true',
361 492 )
362 493 );
363 494
495 + // --- Public scan signals -----------------------------------------
496 + // One tiny unauthenticated JSON body for external audit tools (the
497 + // speed scanner on xspeedcache.com): plugin version, whether the MCP
498 + // server is connected, and whether the site is attached to xSpeed
499 + // Hub. Everything except `hub` is already publicly discoverable —
500 + // the cache signature carries the version and /mcp answers 401 when
501 + // connected — and `hub` is a bare boolean. No tokens, accounts or
502 + // emails leave through this route.
503 + register_rest_route(
504 + self::NS,
505 + '/signals',
506 + array(
507 + 'methods' => 'GET',
508 + 'callback' => array( $this, 'rest_signals' ),
509 + 'permission_callback' => '__return_true',
510 + )
511 + );
512 +
364 513 // --- Admin-only management routes (dashboard) --------------------
365 514 register_rest_route(
366 515 self::NS,
367 516 '/mcp/connection',
@@ -546,13 +695,49 @@
546 695 'permission_callback' => '__return_true',
547 696 )
548 697 );
549 698
699 + // --- OAuth discovery, REST fallback ------------------------------
700 + // The canonical documents live at /.well-known/… via rewrite rules.
701 + // Many hosts own that prefix for ACME/Let's Encrypt (an nginx
702 + // `location ^~ /.well-known` block, or an edge redirect rule), which
703 + // swallows the request before WordPress ever runs — the pretty URL
704 + // then 404s or redirects to the homepage no matter how the plugin is
705 + // configured, and OAuth discovery dead-ends with no way back.
706 + // Serving the same two documents under /wp-json puts them on a path
707 + // no ACME tooling claims, so discovery still completes there.
708 + register_rest_route(
709 + self::NS,
710 + '/mcp/.well-known/oauth-protected-resource',
711 + array(
712 + 'methods' => 'GET',
713 + 'callback' => array( $this, 'rest_protected_resource_metadata' ),
714 + 'permission_callback' => '__return_true',
715 + )
716 + );
717 + register_rest_route(
718 + self::NS,
719 + '/mcp/.well-known/oauth-authorization-server',
720 + array(
721 + 'methods' => 'GET',
722 + 'callback' => array( $this, 'rest_authorization_server_metadata' ),
723 + 'permission_callback' => '__return_true',
724 + )
725 + );
726 +
550 727 // --- MCP-token-only tool routes (optional hosted-broker path) ----
551 728 $tool_perm = array( Mcp_Auth::class, 'permission' );
552 729 register_rest_route(
553 730 self::NS,
554 - '/mcp/tool/(?P<tool>[a-z_]+)',
731 + // [a-z0-9_-]+ — the HYPHEN is the one that matters, not the digit.
732 + // Generated tool names carry their module slug verbatim, and 33 of
733 + // the 92 in the catalog have a hyphenated slug
734 + // (xspeed_cache-404_status, xspeed_migration-pro_apply,
735 + // xspeed_smart-predict_status …). Every one of those returned
736 + // rest_no_route through the broker path. The earlier widening to
737 + // [a-z0-9_]+ un-blocked nothing: the only digit-bearing name is
738 + // cache-404, whose problem was the hyphen. (QA on #158) */
739 + '/mcp/tool/(?P<tool>[a-z0-9_-]+)',
555 740 array(
556 741 array(
557 742 'methods' => 'GET',
558 743 'callback' => array( $this, 'rest_tool' ),
@@ -592,8 +777,35 @@
592 777 return $response;
593 778 }
594 779
595 780 /**
781 + * GET /signals — the public scan-signals body. See the route
782 + * registration for what may (and may not) leave through it.
783 + *
784 + * @return \WP_REST_Response
785 + */
786 + public function rest_signals() {
787 + $signals = array(
788 + 'xspeed' => XSPEED_VERSION,
789 + 'mcp' => '' !== Mcp_Pairing::site_token(),
790 + 'hub' => Mcp_Hub::site_attached(),
791 + );
792 +
793 + /**
794 + * Filter the public scan signals.
795 + *
796 + * Lets an add-on append its own public facts (e.g. its version
797 + * under `pro`). Values returned here are served UNAUTHENTICATED —
798 + * never add tokens, accounts, emails, or paths.
799 + *
800 + * @param array<string,mixed> $signals The signals body.
801 + */
802 + $signals = (array) apply_filters( 'xspeed_scan_signals', $signals );
803 +
804 + return rest_ensure_response( $signals );
805 + }
806 +
807 + /**
596 808 * GET /mcp/connection — pairing status for the dashboard.
597 809 *
598 810 * @param \WP_REST_Request $request Unused.
599 811 * @return \WP_REST_Response
@@ -784,8 +996,41 @@
784 996
785 997 // -- OAuth 2.1 handlers ------------------------------------------------
786 998
787 999 /**
1000 + * GET /mcp/.well-known/oauth-protected-resource — RFC 9728 metadata.
1001 + *
1002 + * Byte-identical to what the /.well-known rewrite serves; both call the
1003 + * same builder so the two locations can never drift.
1004 + *
1005 + * @return \WP_REST_Response
1006 + */
1007 + public function rest_protected_resource_metadata(): \WP_REST_Response {
1008 + return $this->discovery_response( Mcp_OAuth::protected_resource_metadata() );
1009 + }
1010 +
1011 + /**
1012 + * GET /mcp/.well-known/oauth-authorization-server — RFC 8414 metadata.
1013 + *
1014 + * @return \WP_REST_Response
1015 + */
1016 + public function rest_authorization_server_metadata(): \WP_REST_Response {
1017 + return $this->discovery_response( Mcp_OAuth::authorization_server_metadata() );
1018 + }
1019 +
1020 + /**
1021 + * Wrap a discovery document in a public, cacheable REST response.
1022 + *
1023 + * @param array<string,mixed> $data The metadata document.
1024 + * @return \WP_REST_Response
1025 + */
1026 + private function discovery_response( array $data ): \WP_REST_Response {
1027 + $response = new \WP_REST_Response( $data, 200 );
1028 + $response->header( 'Cache-Control', 'public, max-age=3600' );
1029 + return $response;
1030 + }
1031 +
1032 + /**
788 1033 * POST /mcp/oauth/register — RFC 7591 dynamic client registration.
789 1034 *
790 1035 * @param \WP_REST_Request $request JSON body with redirect_uris.
791 1036 * @return \WP_REST_Response|\WP_Error
@@ -1245,6 +1490,27 @@
1245 1490 public function cli_disconnect( array $args, array $assoc ): void {
1246 1491 unset( $args, $assoc );
1247 1492 Mcp_Pairing::disconnect();
1248 1493 \WP_CLI::success( 'Disconnected and revoked the MCP token.' );
1494 + }
1495 +
1496 + /**
1497 + * MCP is on when a connection token exists -- it has no `enabled`
1498 + * setting, so the sidebar counted the AI group as empty on a site with
1499 + * a live read-write AI connection. Reads the same
1500 + * `Mcp_Pairing::public_status()` the CLI and the panel do, so the count
1501 + * cannot disagree with the badge on the panel. (#363)
1502 + */
1503 + public function is_active(): ?bool {
1504 + $status = Mcp_Pairing::public_status();
1505 + return ! empty( $status['connected'] );
1506 + }
1507 +
1508 + /**
1509 + * MCP has no on/off setting -- it is on when a connection exists.
1510 + */
1511 + public function active_reason(): ?string {
1512 + return $this->is_active()
1513 + ? __( 'An AI assistant is connected to this site. This module counts as on whenever a connection token exists, rather than having its own on/off setting.', 'xspeed' )
1514 + : __( 'No AI assistant is connected. This module counts as on once you connect one.', 'xspeed' );
1249 1515 }
1250 1516 }